Merge "docs: mw.widgets.CategorySelector: Fix example code"
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Database
25 */
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28
29 /**
30 * Database abstraction object
31 * @ingroup Database
32 */
33 abstract class DatabaseBase implements IDatabase, LoggerAwareInterface {
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES = 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX = 1500000;
40
41 /** How long before it is worth doing a dummy query to test the connection */
42 const PING_TTL = 1.0;
43 const PING_QUERY = 'SELECT 1 AS ping';
44
45 const TINY_WRITE_SEC = .010;
46 const SLOW_WRITE_SEC = .500;
47 const SMALL_WRITE_ROWS = 100;
48
49 /** @var string SQL query */
50 protected $mLastQuery = '';
51 /** @var bool */
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
55 /** @var string */
56 protected $mServer;
57 /** @var string */
58 protected $mUser;
59 /** @var string */
60 protected $mPassword;
61 /** @var string */
62 protected $mDBname;
63 /** @var bool */
64 protected $cliMode;
65
66 /** @var BagOStuff APC cache */
67 protected $srvCache;
68 /** @var LoggerInterface */
69 protected $connLogger;
70 /** @var LoggerInterface */
71 protected $queryLogger;
72 /** @var callback Error logging callback */
73 protected $errorLogger;
74
75 /** @var resource Database connection */
76 protected $mConn = null;
77 /** @var bool */
78 protected $mOpened = false;
79
80 /** @var array[] List of (callable, method name) */
81 protected $mTrxIdleCallbacks = [];
82 /** @var array[] List of (callable, method name) */
83 protected $mTrxPreCommitCallbacks = [];
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxEndCallbacks = [];
86 /** @var array[] Map of (name => (callable, method name)) */
87 protected $mTrxRecurringCallbacks = [];
88 /** @var bool Whether to suppress triggering of transaction end callbacks */
89 protected $mTrxEndCallbacksSuppressed = false;
90
91 /** @var string */
92 protected $mTablePrefix;
93 /** @var string */
94 protected $mSchema;
95 /** @var integer */
96 protected $mFlags;
97 /** @var bool */
98 protected $mForeign;
99 /** @var array */
100 protected $mLBInfo = [];
101 /** @var bool|null */
102 protected $mDefaultBigSelects = null;
103 /** @var array|bool */
104 protected $mSchemaVars = false;
105 /** @var array */
106 protected $mSessionVars = [];
107 /** @var array|null */
108 protected $preparedArgs;
109 /** @var string|bool|null Stashed value of html_errors INI setting */
110 protected $htmlErrors;
111 /** @var string */
112 protected $delimiter = ';';
113
114 /**
115 * Either 1 if a transaction is active or 0 otherwise.
116 * The other Trx fields may not be meaningfull if this is 0.
117 *
118 * @var int
119 */
120 protected $mTrxLevel = 0;
121 /**
122 * Either a short hexidecimal string if a transaction is active or ""
123 *
124 * @var string
125 * @see DatabaseBase::mTrxLevel
126 */
127 protected $mTrxShortId = '';
128 /**
129 * The UNIX time that the transaction started. Callers can assume that if
130 * snapshot isolation is used, then the data is *at least* up to date to that
131 * point (possibly more up-to-date since the first SELECT defines the snapshot).
132 *
133 * @var float|null
134 * @see DatabaseBase::mTrxLevel
135 */
136 private $mTrxTimestamp = null;
137 /** @var float Lag estimate at the time of BEGIN */
138 private $mTrxReplicaLag = null;
139 /**
140 * Remembers the function name given for starting the most recent transaction via begin().
141 * Used to provide additional context for error reporting.
142 *
143 * @var string
144 * @see DatabaseBase::mTrxLevel
145 */
146 private $mTrxFname = null;
147 /**
148 * Record if possible write queries were done in the last transaction started
149 *
150 * @var bool
151 * @see DatabaseBase::mTrxLevel
152 */
153 private $mTrxDoneWrites = false;
154 /**
155 * Record if the current transaction was started implicitly due to DBO_TRX being set.
156 *
157 * @var bool
158 * @see DatabaseBase::mTrxLevel
159 */
160 private $mTrxAutomatic = false;
161 /**
162 * Array of levels of atomicity within transactions
163 *
164 * @var array
165 */
166 private $mTrxAtomicLevels = [];
167 /**
168 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
169 *
170 * @var bool
171 */
172 private $mTrxAutomaticAtomic = false;
173 /**
174 * Track the write query callers of the current transaction
175 *
176 * @var string[]
177 */
178 private $mTrxWriteCallers = [];
179 /**
180 * @var float Seconds spent in write queries for the current transaction
181 */
182 private $mTrxWriteDuration = 0.0;
183 /**
184 * @var integer Number of write queries for the current transaction
185 */
186 private $mTrxWriteQueryCount = 0;
187 /**
188 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
189 */
190 private $mTrxWriteAdjDuration = 0.0;
191 /**
192 * @var integer Number of write queries counted in mTrxWriteAdjDuration
193 */
194 private $mTrxWriteAdjQueryCount = 0;
195 /**
196 * @var float RTT time estimate
197 */
198 private $mRTTEstimate = 0.0;
199
200 /** @var array Map of (name => 1) for locks obtained via lock() */
201 private $mNamedLocksHeld = [];
202
203 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
204 private $lazyMasterHandle;
205
206 /**
207 * @since 1.21
208 * @var resource File handle for upgrade
209 */
210 protected $fileHandle = null;
211
212 /**
213 * @since 1.22
214 * @var string[] Process cache of VIEWs names in the database
215 */
216 protected $allViews = null;
217
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
220
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
223
224 /** @var Profiler */
225 protected $profiler;
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
228
229 /**
230 * Constructor.
231 *
232 * FIXME: It is possible to construct a Database object with no associated
233 * connection object, by specifying no parameters to __construct(). This
234 * feature is deprecated and should be removed.
235 *
236 * IDatabase classes should not be constructed directly in external
237 * code. DatabaseBase::factory() should be used instead.
238 *
239 * @param array $params Parameters passed from DatabaseBase::factory()
240 */
241 function __construct( array $params ) {
242 $server = $params['host'];
243 $user = $params['user'];
244 $password = $params['password'];
245 $dbName = $params['dbname'];
246 $flags = $params['flags'];
247
248 $this->mSchema = $params['schema'];
249 $this->mTablePrefix = $params['tablePrefix'];
250
251 $this->cliMode = isset( $params['cliMode'] )
252 ? $params['cliMode']
253 : ( PHP_SAPI === 'cli' );
254
255 $this->mFlags = $flags;
256 if ( $this->mFlags & DBO_DEFAULT ) {
257 if ( $this->cliMode ) {
258 $this->mFlags &= ~DBO_TRX;
259 } else {
260 $this->mFlags |= DBO_TRX;
261 }
262 }
263
264 $this->mSessionVars = $params['variables'];
265
266 $this->mForeign = $params['foreign'];
267
268 $this->srvCache = isset( $params['srvCache'] )
269 ? $params['srvCache']
270 : new EmptyBagOStuff();
271
272 $this->profiler = isset( $params['profiler'] )
273 ? $params['profiler']
274 : Profiler::instance(); // @TODO: remove global state
275 $this->trxProfiler = isset( $params['trxProfiler'] )
276 ? $params['trxProfiler']
277 : new TransactionProfiler();
278 $this->connLogger = isset( $params['connLogger'] )
279 ? $params['connLogger']
280 : new \Psr\Log\NullLogger();
281 $this->queryLogger = isset( $params['queryLogger'] )
282 ? $params['queryLogger']
283 : new \Psr\Log\NullLogger();
284
285 if ( $user ) {
286 $this->open( $server, $user, $password, $dbName );
287 }
288 }
289
290 /**
291 * Given a DB type, construct the name of the appropriate child class of
292 * IDatabase. This is designed to replace all of the manual stuff like:
293 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
294 * as well as validate against the canonical list of DB types we have
295 *
296 * This factory function is mostly useful for when you need to connect to a
297 * database other than the MediaWiki default (such as for external auth,
298 * an extension, et cetera). Do not use this to connect to the MediaWiki
299 * database. Example uses in core:
300 * @see LoadBalancer::reallyOpenConnection()
301 * @see ForeignDBRepo::getMasterDB()
302 * @see WebInstallerDBConnect::execute()
303 *
304 * @since 1.18
305 *
306 * @param string $dbType A possible DB type
307 * @param array $p An array of options to pass to the constructor.
308 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
309 * @return IDatabase|null If the database driver or extension cannot be found
310 * @throws InvalidArgumentException If the database driver or extension cannot be found
311 */
312 final public static function factory( $dbType, $p = [] ) {
313 global $wgCommandLineMode;
314
315 $canonicalDBTypes = [
316 'mysql' => [ 'mysqli', 'mysql' ],
317 'postgres' => [],
318 'sqlite' => [],
319 'oracle' => [],
320 'mssql' => [],
321 ];
322
323 $driver = false;
324 $dbType = strtolower( $dbType );
325 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
326 $possibleDrivers = $canonicalDBTypes[$dbType];
327 if ( !empty( $p['driver'] ) ) {
328 if ( in_array( $p['driver'], $possibleDrivers ) ) {
329 $driver = $p['driver'];
330 } else {
331 throw new InvalidArgumentException( __METHOD__ .
332 " type '$dbType' does not support driver '{$p['driver']}'" );
333 }
334 } else {
335 foreach ( $possibleDrivers as $posDriver ) {
336 if ( extension_loaded( $posDriver ) ) {
337 $driver = $posDriver;
338 break;
339 }
340 }
341 }
342 } else {
343 $driver = $dbType;
344 }
345 if ( $driver === false ) {
346 throw new InvalidArgumentException( __METHOD__ .
347 " no viable database extension found for type '$dbType'" );
348 }
349
350 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
351 // and everything else doesn't use a schema (e.g. null)
352 // Although postgres and oracle support schemas, we don't use them (yet)
353 // to maintain backwards compatibility
354 $defaultSchemas = [
355 'mssql' => 'get from global',
356 ];
357
358 $class = 'Database' . ucfirst( $driver );
359 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
360 // Resolve some defaults for b/c
361 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
362 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
363 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
364 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
365 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
366 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
367 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
368 if ( !isset( $p['schema'] ) ) {
369 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
370 }
371 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
372 $p['cliMode'] = $wgCommandLineMode;
373
374 $conn = new $class( $p );
375 if ( isset( $p['connLogger'] ) ) {
376 $conn->connLogger = $p['connLogger'];
377 }
378 if ( isset( $p['queryLogger'] ) ) {
379 $conn->queryLogger = $p['queryLogger'];
380 }
381 if ( isset( $p['errorLogger'] ) ) {
382 $conn->errorLogger = $p['errorLogger'];
383 } else {
384 $conn->errorLogger = [ MWExceptionHandler::class, 'logException' ];
385 }
386 } else {
387 $conn = null;
388 }
389
390 return $conn;
391 }
392
393 public function setLogger( LoggerInterface $logger ) {
394 $this->queryLogger = $logger;
395 }
396
397 public function getServerInfo() {
398 return $this->getServerVersion();
399 }
400
401 /**
402 * @return string Command delimiter used by this database engine
403 */
404 public function getDelimiter() {
405 return $this->delimiter;
406 }
407
408 /**
409 * Boolean, controls output of large amounts of debug information.
410 * @param bool|null $debug
411 * - true to enable debugging
412 * - false to disable debugging
413 * - omitted or null to do nothing
414 *
415 * @return bool|null Previous value of the flag
416 */
417 public function debug( $debug = null ) {
418 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
419 }
420
421 public function bufferResults( $buffer = null ) {
422 if ( is_null( $buffer ) ) {
423 return !(bool)( $this->mFlags & DBO_NOBUFFER );
424 } else {
425 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
426 }
427 }
428
429 /**
430 * Turns on (false) or off (true) the automatic generation and sending
431 * of a "we're sorry, but there has been a database error" page on
432 * database errors. Default is on (false). When turned off, the
433 * code should use lastErrno() and lastError() to handle the
434 * situation as appropriate.
435 *
436 * Do not use this function outside of the Database classes.
437 *
438 * @param null|bool $ignoreErrors
439 * @return bool The previous value of the flag.
440 */
441 protected function ignoreErrors( $ignoreErrors = null ) {
442 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
443 }
444
445 public function trxLevel() {
446 return $this->mTrxLevel;
447 }
448
449 public function trxTimestamp() {
450 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
451 }
452
453 public function tablePrefix( $prefix = null ) {
454 return wfSetVar( $this->mTablePrefix, $prefix );
455 }
456
457 public function dbSchema( $schema = null ) {
458 return wfSetVar( $this->mSchema, $schema );
459 }
460
461 /**
462 * Set the filehandle to copy write statements to.
463 *
464 * @param resource $fh File handle
465 */
466 public function setFileHandle( $fh ) {
467 $this->fileHandle = $fh;
468 }
469
470 public function getLBInfo( $name = null ) {
471 if ( is_null( $name ) ) {
472 return $this->mLBInfo;
473 } else {
474 if ( array_key_exists( $name, $this->mLBInfo ) ) {
475 return $this->mLBInfo[$name];
476 } else {
477 return null;
478 }
479 }
480 }
481
482 public function setLBInfo( $name, $value = null ) {
483 if ( is_null( $value ) ) {
484 $this->mLBInfo = $name;
485 } else {
486 $this->mLBInfo[$name] = $value;
487 }
488 }
489
490 public function setLazyMasterHandle( IDatabase $conn ) {
491 $this->lazyMasterHandle = $conn;
492 }
493
494 /**
495 * @return IDatabase|null
496 * @see setLazyMasterHandle()
497 * @since 1.27
498 */
499 public function getLazyMasterHandle() {
500 return $this->lazyMasterHandle;
501 }
502
503 /**
504 * @param TransactionProfiler $profiler
505 * @since 1.27
506 */
507 public function setTransactionProfiler( TransactionProfiler $profiler ) {
508 $this->trxProfiler = $profiler;
509 }
510
511 /**
512 * Returns true if this database supports (and uses) cascading deletes
513 *
514 * @return bool
515 */
516 public function cascadingDeletes() {
517 return false;
518 }
519
520 /**
521 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
522 *
523 * @return bool
524 */
525 public function cleanupTriggers() {
526 return false;
527 }
528
529 /**
530 * Returns true if this database is strict about what can be put into an IP field.
531 * Specifically, it uses a NULL value instead of an empty string.
532 *
533 * @return bool
534 */
535 public function strictIPs() {
536 return false;
537 }
538
539 /**
540 * Returns true if this database uses timestamps rather than integers
541 *
542 * @return bool
543 */
544 public function realTimestamps() {
545 return false;
546 }
547
548 public function implicitGroupby() {
549 return true;
550 }
551
552 public function implicitOrderby() {
553 return true;
554 }
555
556 /**
557 * Returns true if this database can do a native search on IP columns
558 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
559 *
560 * @return bool
561 */
562 public function searchableIPs() {
563 return false;
564 }
565
566 /**
567 * Returns true if this database can use functional indexes
568 *
569 * @return bool
570 */
571 public function functionalIndexes() {
572 return false;
573 }
574
575 public function lastQuery() {
576 return $this->mLastQuery;
577 }
578
579 public function doneWrites() {
580 return (bool)$this->mDoneWrites;
581 }
582
583 public function lastDoneWrites() {
584 return $this->mDoneWrites ?: false;
585 }
586
587 public function writesPending() {
588 return $this->mTrxLevel && $this->mTrxDoneWrites;
589 }
590
591 public function writesOrCallbacksPending() {
592 return $this->mTrxLevel && (
593 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
594 );
595 }
596
597 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
598 if ( !$this->mTrxLevel ) {
599 return false;
600 } elseif ( !$this->mTrxDoneWrites ) {
601 return 0.0;
602 }
603
604 switch ( $type ) {
605 case self::ESTIMATE_DB_APPLY:
606 $this->ping( $rtt );
607 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
608 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
609 // For omitted queries, make them count as something at least
610 $omitted = $this->mTrxWriteQueryCount - $this->mTrxWriteAdjQueryCount;
611 $applyTime += self::TINY_WRITE_SEC * $omitted;
612
613 return $applyTime;
614 default: // everything
615 return $this->mTrxWriteDuration;
616 }
617 }
618
619 public function pendingWriteCallers() {
620 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
621 }
622
623 public function isOpen() {
624 return $this->mOpened;
625 }
626
627 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
628 if ( $remember === self::REMEMBER_PRIOR ) {
629 array_push( $this->priorFlags, $this->mFlags );
630 }
631 $this->mFlags |= $flag;
632 }
633
634 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
635 if ( $remember === self::REMEMBER_PRIOR ) {
636 array_push( $this->priorFlags, $this->mFlags );
637 }
638 $this->mFlags &= ~$flag;
639 }
640
641 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
642 if ( !$this->priorFlags ) {
643 return;
644 }
645
646 if ( $state === self::RESTORE_INITIAL ) {
647 $this->mFlags = reset( $this->priorFlags );
648 $this->priorFlags = [];
649 } else {
650 $this->mFlags = array_pop( $this->priorFlags );
651 }
652 }
653
654 public function getFlag( $flag ) {
655 return !!( $this->mFlags & $flag );
656 }
657
658 public function getProperty( $name ) {
659 return $this->$name;
660 }
661
662 public function getWikiID() {
663 if ( $this->mTablePrefix ) {
664 return "{$this->mDBname}-{$this->mTablePrefix}";
665 } else {
666 return $this->mDBname;
667 }
668 }
669
670 /**
671 * Return a path to the DBMS-specific SQL file if it exists,
672 * otherwise default SQL file
673 *
674 * @param string $filename
675 * @return string
676 */
677 private function getSqlFilePath( $filename ) {
678 global $IP;
679 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
680 if ( file_exists( $dbmsSpecificFilePath ) ) {
681 return $dbmsSpecificFilePath;
682 } else {
683 return "$IP/maintenance/$filename";
684 }
685 }
686
687 /**
688 * Return a path to the DBMS-specific schema file,
689 * otherwise default to tables.sql
690 *
691 * @return string
692 */
693 public function getSchemaPath() {
694 return $this->getSqlFilePath( 'tables.sql' );
695 }
696
697 /**
698 * Return a path to the DBMS-specific update key file,
699 * otherwise default to update-keys.sql
700 *
701 * @return string
702 */
703 public function getUpdateKeysPath() {
704 return $this->getSqlFilePath( 'update-keys.sql' );
705 }
706
707 /**
708 * Get information about an index into an object
709 * @param string $table Table name
710 * @param string $index Index name
711 * @param string $fname Calling function name
712 * @return mixed Database-specific index description class or false if the index does not exist
713 */
714 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
715
716 /**
717 * Wrapper for addslashes()
718 *
719 * @param string $s String to be slashed.
720 * @return string Slashed string.
721 */
722 abstract function strencode( $s );
723
724 /**
725 * Called by serialize. Throw an exception when DB connection is serialized.
726 * This causes problems on some database engines because the connection is
727 * not restored on unserialize.
728 */
729 public function __sleep() {
730 throw new RuntimeException( 'Database serialization may cause problems, since ' .
731 'the connection is not restored on wakeup.' );
732 }
733
734 protected function installErrorHandler() {
735 $this->mPHPError = false;
736 $this->htmlErrors = ini_set( 'html_errors', '0' );
737 set_error_handler( [ $this, 'connectionerrorLogger' ] );
738 }
739
740 /**
741 * @return bool|string
742 */
743 protected function restoreErrorHandler() {
744 restore_error_handler();
745 if ( $this->htmlErrors !== false ) {
746 ini_set( 'html_errors', $this->htmlErrors );
747 }
748 if ( $this->mPHPError ) {
749 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
750 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
751
752 return $error;
753 } else {
754 return false;
755 }
756 }
757
758 /**
759 * @param int $errno
760 * @param string $errstr
761 */
762 public function connectionerrorLogger( $errno, $errstr ) {
763 $this->mPHPError = $errstr;
764 }
765
766 /**
767 * Create a log context to pass to PSR logging functions.
768 *
769 * @param array $extras Additional data to add to context
770 * @return array
771 */
772 protected function getLogContext( array $extras = [] ) {
773 return array_merge(
774 [
775 'db_server' => $this->mServer,
776 'db_name' => $this->mDBname,
777 'db_user' => $this->mUser,
778 ],
779 $extras
780 );
781 }
782
783 public function close() {
784 if ( $this->mConn ) {
785 if ( $this->trxLevel() ) {
786 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
787 }
788
789 $closed = $this->closeConnection();
790 $this->mConn = false;
791 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
792 throw new RuntimeException( "Transaction callbacks still pending." );
793 } else {
794 $closed = true;
795 }
796 $this->mOpened = false;
797
798 return $closed;
799 }
800
801 /**
802 * Make sure isOpen() returns true as a sanity check
803 *
804 * @throws DBUnexpectedError
805 */
806 protected function assertOpen() {
807 if ( !$this->isOpen() ) {
808 throw new DBUnexpectedError( $this, "DB connection was already closed." );
809 }
810 }
811
812 /**
813 * Closes underlying database connection
814 * @since 1.20
815 * @return bool Whether connection was closed successfully
816 */
817 abstract protected function closeConnection();
818
819 function reportConnectionError( $error = 'Unknown error' ) {
820 $myError = $this->lastError();
821 if ( $myError ) {
822 $error = $myError;
823 }
824
825 # New method
826 throw new DBConnectionError( $this, $error );
827 }
828
829 /**
830 * The DBMS-dependent part of query()
831 *
832 * @param string $sql SQL query.
833 * @return ResultWrapper|bool Result object to feed to fetchObject,
834 * fetchRow, ...; or false on failure
835 */
836 abstract protected function doQuery( $sql );
837
838 /**
839 * Determine whether a query writes to the DB.
840 * Should return true if unsure.
841 *
842 * @param string $sql
843 * @return bool
844 */
845 protected function isWriteQuery( $sql ) {
846 return !preg_match(
847 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
848 }
849
850 /**
851 * @param $sql
852 * @return string|null
853 */
854 protected function getQueryVerb( $sql ) {
855 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
856 }
857
858 /**
859 * Determine whether a SQL statement is sensitive to isolation level.
860 * A SQL statement is considered transactable if its result could vary
861 * depending on the transaction isolation level. Operational commands
862 * such as 'SET' and 'SHOW' are not considered to be transactable.
863 *
864 * @param string $sql
865 * @return bool
866 */
867 protected function isTransactableQuery( $sql ) {
868 $verb = $this->getQueryVerb( $sql );
869 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
870 }
871
872 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
873 global $wgUser;
874
875 $priorWritesPending = $this->writesOrCallbacksPending();
876 $this->mLastQuery = $sql;
877
878 $isWrite = $this->isWriteQuery( $sql );
879 if ( $isWrite ) {
880 $reason = $this->getReadOnlyReason();
881 if ( $reason !== false ) {
882 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
883 }
884 # Set a flag indicating that writes have been done
885 $this->mDoneWrites = microtime( true );
886 }
887
888 # Add a comment for easy SHOW PROCESSLIST interpretation
889 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
890 $userName = $wgUser->getName();
891 if ( mb_strlen( $userName ) > 15 ) {
892 $userName = mb_substr( $userName, 0, 15 ) . '...';
893 }
894 $userName = str_replace( '/', '', $userName );
895 } else {
896 $userName = '';
897 }
898
899 // Add trace comment to the begin of the sql string, right after the operator.
900 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
901 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
902
903 # Start implicit transactions that wrap the request if DBO_TRX is enabled
904 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX )
905 && $this->isTransactableQuery( $sql )
906 ) {
907 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
908 $this->mTrxAutomatic = true;
909 }
910
911 # Keep track of whether the transaction has write queries pending
912 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
913 $this->mTrxDoneWrites = true;
914 $this->trxProfiler->transactionWritingIn(
915 $this->mServer, $this->mDBname, $this->mTrxShortId );
916 }
917
918 if ( $this->debug() ) {
919 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
920 }
921
922 # Avoid fatals if close() was called
923 $this->assertOpen();
924
925 # Send the query to the server
926 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
927
928 # Try reconnecting if the connection was lost
929 if ( false === $ret && $this->wasErrorReissuable() ) {
930 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
931 # Stash the last error values before anything might clear them
932 $lastError = $this->lastError();
933 $lastErrno = $this->lastErrno();
934 # Update state tracking to reflect transaction loss due to disconnection
935 $this->handleTransactionLoss();
936 if ( $this->reconnect() ) {
937 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
938 $this->connLogger->warning( $msg );
939 $this->queryLogger->warning(
940 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
941
942 if ( !$recoverable ) {
943 # Callers may catch the exception and continue to use the DB
944 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
945 } else {
946 # Should be safe to silently retry the query
947 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
948 }
949 } else {
950 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
951 $this->connLogger->error( $msg );
952 }
953 }
954
955 if ( false === $ret ) {
956 # Deadlocks cause the entire transaction to abort, not just the statement.
957 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
958 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
959 if ( $this->wasDeadlock() ) {
960 if ( $this->explicitTrxActive() || $priorWritesPending ) {
961 $tempIgnore = false; // not recoverable
962 }
963 # Update state tracking to reflect transaction loss
964 $this->handleTransactionLoss();
965 }
966
967 $this->reportQueryError(
968 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
969 }
970
971 $res = $this->resultObject( $ret );
972
973 return $res;
974 }
975
976 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
977 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
978 # generalizeSQL() will probably cut down the query to reasonable
979 # logging size most of the time. The substr is really just a sanity check.
980 if ( $isMaster ) {
981 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
982 } else {
983 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
984 }
985
986 # Include query transaction state
987 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
988
989 $startTime = microtime( true );
990 $this->profiler->profileIn( $queryProf );
991 $ret = $this->doQuery( $commentedSql );
992 $this->profiler->profileOut( $queryProf );
993 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
994
995 unset( $queryProfSection ); // profile out (if set)
996
997 if ( $ret !== false ) {
998 $this->lastPing = $startTime;
999 if ( $isWrite && $this->mTrxLevel ) {
1000 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
1001 $this->mTrxWriteCallers[] = $fname;
1002 }
1003 }
1004
1005 if ( $sql === self::PING_QUERY ) {
1006 $this->mRTTEstimate = $queryRuntime;
1007 }
1008
1009 $this->trxProfiler->recordQueryCompletion(
1010 $queryProf, $startTime, $isWrite, $this->affectedRows()
1011 );
1012 MWDebug::query( $sql, $fname, $isMaster, $queryRuntime );
1013
1014 return $ret;
1015 }
1016
1017 /**
1018 * Update the estimated run-time of a query, not counting large row lock times
1019 *
1020 * LoadBalancer can be set to rollback transactions that will create huge replication
1021 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1022 * queries, like inserting a row can take a long time due to row locking. This method
1023 * uses some simple heuristics to discount those cases.
1024 *
1025 * @param string $sql A SQL write query
1026 * @param float $runtime Total runtime, including RTT
1027 */
1028 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1029 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1030 $indicativeOfReplicaRuntime = true;
1031 if ( $runtime > self::SLOW_WRITE_SEC ) {
1032 $verb = $this->getQueryVerb( $sql );
1033 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1034 if ( $verb === 'INSERT' ) {
1035 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1036 } elseif ( $verb === 'REPLACE' ) {
1037 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1038 }
1039 }
1040
1041 $this->mTrxWriteDuration += $runtime;
1042 $this->mTrxWriteQueryCount += 1;
1043 if ( $indicativeOfReplicaRuntime ) {
1044 $this->mTrxWriteAdjDuration += $runtime;
1045 $this->mTrxWriteAdjQueryCount += 1;
1046 }
1047 }
1048
1049 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1050 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1051 # Dropped connections also mean that named locks are automatically released.
1052 # Only allow error suppression in autocommit mode or when the lost transaction
1053 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1054 if ( $this->mNamedLocksHeld ) {
1055 return false; // possible critical section violation
1056 } elseif ( $sql === 'COMMIT' ) {
1057 return !$priorWritesPending; // nothing written anyway? (T127428)
1058 } elseif ( $sql === 'ROLLBACK' ) {
1059 return true; // transaction lost...which is also what was requested :)
1060 } elseif ( $this->explicitTrxActive() ) {
1061 return false; // don't drop atomocity
1062 } elseif ( $priorWritesPending ) {
1063 return false; // prior writes lost from implicit transaction
1064 }
1065
1066 return true;
1067 }
1068
1069 private function handleTransactionLoss() {
1070 $this->mTrxLevel = 0;
1071 $this->mTrxIdleCallbacks = []; // bug 65263
1072 $this->mTrxPreCommitCallbacks = []; // bug 65263
1073 try {
1074 // Handle callbacks in mTrxEndCallbacks
1075 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1076 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1077 return null;
1078 } catch ( Exception $e ) {
1079 // Already logged; move on...
1080 return $e;
1081 }
1082 }
1083
1084 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1085 if ( $this->ignoreErrors() || $tempIgnore ) {
1086 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1087 } else {
1088 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1089 $this->queryLogger->error(
1090 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1091 $this->getLogContext( [
1092 'method' => __METHOD__,
1093 'errno' => $errno,
1094 'error' => $error,
1095 'sql1line' => $sql1line,
1096 'fname' => $fname,
1097 ] )
1098 );
1099 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1100 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1101 }
1102 }
1103
1104 /**
1105 * Intended to be compatible with the PEAR::DB wrapper functions.
1106 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1107 *
1108 * ? = scalar value, quoted as necessary
1109 * ! = raw SQL bit (a function for instance)
1110 * & = filename; reads the file and inserts as a blob
1111 * (we don't use this though...)
1112 *
1113 * @param string $sql
1114 * @param string $func
1115 *
1116 * @return array
1117 */
1118 protected function prepare( $sql, $func = __METHOD__ ) {
1119 /* MySQL doesn't support prepared statements (yet), so just
1120 * pack up the query for reference. We'll manually replace
1121 * the bits later.
1122 */
1123 return [ 'query' => $sql, 'func' => $func ];
1124 }
1125
1126 /**
1127 * Free a prepared query, generated by prepare().
1128 * @param string $prepared
1129 */
1130 protected function freePrepared( $prepared ) {
1131 /* No-op by default */
1132 }
1133
1134 /**
1135 * Execute a prepared query with the various arguments
1136 * @param string $prepared The prepared sql
1137 * @param mixed $args Either an array here, or put scalars as varargs
1138 *
1139 * @return ResultWrapper
1140 */
1141 public function execute( $prepared, $args = null ) {
1142 if ( !is_array( $args ) ) {
1143 # Pull the var args
1144 $args = func_get_args();
1145 array_shift( $args );
1146 }
1147
1148 $sql = $this->fillPrepared( $prepared['query'], $args );
1149
1150 return $this->query( $sql, $prepared['func'] );
1151 }
1152
1153 /**
1154 * For faking prepared SQL statements on DBs that don't support it directly.
1155 *
1156 * @param string $preparedQuery A 'preparable' SQL statement
1157 * @param array $args Array of Arguments to fill it with
1158 * @return string Executable SQL
1159 */
1160 public function fillPrepared( $preparedQuery, $args ) {
1161 reset( $args );
1162 $this->preparedArgs =& $args;
1163
1164 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1165 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1166 }
1167
1168 /**
1169 * preg_callback func for fillPrepared()
1170 * The arguments should be in $this->preparedArgs and must not be touched
1171 * while we're doing this.
1172 *
1173 * @param array $matches
1174 * @throws DBUnexpectedError
1175 * @return string
1176 */
1177 protected function fillPreparedArg( $matches ) {
1178 switch ( $matches[1] ) {
1179 case '\\?':
1180 return '?';
1181 case '\\!':
1182 return '!';
1183 case '\\&':
1184 return '&';
1185 }
1186
1187 list( /* $n */, $arg ) = each( $this->preparedArgs );
1188
1189 switch ( $matches[1] ) {
1190 case '?':
1191 return $this->addQuotes( $arg );
1192 case '!':
1193 return $arg;
1194 case '&':
1195 # return $this->addQuotes( file_get_contents( $arg ) );
1196 throw new DBUnexpectedError(
1197 $this,
1198 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1199 );
1200 default:
1201 throw new DBUnexpectedError(
1202 $this,
1203 'Received invalid match. This should never happen!'
1204 );
1205 }
1206 }
1207
1208 public function freeResult( $res ) {
1209 }
1210
1211 public function selectField(
1212 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1213 ) {
1214 if ( $var === '*' ) { // sanity
1215 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1216 }
1217
1218 if ( !is_array( $options ) ) {
1219 $options = [ $options ];
1220 }
1221
1222 $options['LIMIT'] = 1;
1223
1224 $res = $this->select( $table, $var, $cond, $fname, $options );
1225 if ( $res === false || !$this->numRows( $res ) ) {
1226 return false;
1227 }
1228
1229 $row = $this->fetchRow( $res );
1230
1231 if ( $row !== false ) {
1232 return reset( $row );
1233 } else {
1234 return false;
1235 }
1236 }
1237
1238 public function selectFieldValues(
1239 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1240 ) {
1241 if ( $var === '*' ) { // sanity
1242 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1243 } elseif ( !is_string( $var ) ) { // sanity
1244 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1245 }
1246
1247 if ( !is_array( $options ) ) {
1248 $options = [ $options ];
1249 }
1250
1251 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1252 if ( $res === false ) {
1253 return false;
1254 }
1255
1256 $values = [];
1257 foreach ( $res as $row ) {
1258 $values[] = $row->$var;
1259 }
1260
1261 return $values;
1262 }
1263
1264 /**
1265 * Returns an optional USE INDEX clause to go after the table, and a
1266 * string to go at the end of the query.
1267 *
1268 * @param array $options Associative array of options to be turned into
1269 * an SQL query, valid keys are listed in the function.
1270 * @return array
1271 * @see DatabaseBase::select()
1272 */
1273 public function makeSelectOptions( $options ) {
1274 $preLimitTail = $postLimitTail = '';
1275 $startOpts = '';
1276
1277 $noKeyOptions = [];
1278
1279 foreach ( $options as $key => $option ) {
1280 if ( is_numeric( $key ) ) {
1281 $noKeyOptions[$option] = true;
1282 }
1283 }
1284
1285 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1286
1287 $preLimitTail .= $this->makeOrderBy( $options );
1288
1289 // if (isset($options['LIMIT'])) {
1290 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1291 // isset($options['OFFSET']) ? $options['OFFSET']
1292 // : false);
1293 // }
1294
1295 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1296 $postLimitTail .= ' FOR UPDATE';
1297 }
1298
1299 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1300 $postLimitTail .= ' LOCK IN SHARE MODE';
1301 }
1302
1303 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1304 $startOpts .= 'DISTINCT';
1305 }
1306
1307 # Various MySQL extensions
1308 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1309 $startOpts .= ' /*! STRAIGHT_JOIN */';
1310 }
1311
1312 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1313 $startOpts .= ' HIGH_PRIORITY';
1314 }
1315
1316 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1317 $startOpts .= ' SQL_BIG_RESULT';
1318 }
1319
1320 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1321 $startOpts .= ' SQL_BUFFER_RESULT';
1322 }
1323
1324 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1325 $startOpts .= ' SQL_SMALL_RESULT';
1326 }
1327
1328 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1329 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1330 }
1331
1332 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1333 $startOpts .= ' SQL_CACHE';
1334 }
1335
1336 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1337 $startOpts .= ' SQL_NO_CACHE';
1338 }
1339
1340 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1341 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1342 } else {
1343 $useIndex = '';
1344 }
1345 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1346 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1347 } else {
1348 $ignoreIndex = '';
1349 }
1350
1351 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1352 }
1353
1354 /**
1355 * Returns an optional GROUP BY with an optional HAVING
1356 *
1357 * @param array $options Associative array of options
1358 * @return string
1359 * @see DatabaseBase::select()
1360 * @since 1.21
1361 */
1362 public function makeGroupByWithHaving( $options ) {
1363 $sql = '';
1364 if ( isset( $options['GROUP BY'] ) ) {
1365 $gb = is_array( $options['GROUP BY'] )
1366 ? implode( ',', $options['GROUP BY'] )
1367 : $options['GROUP BY'];
1368 $sql .= ' GROUP BY ' . $gb;
1369 }
1370 if ( isset( $options['HAVING'] ) ) {
1371 $having = is_array( $options['HAVING'] )
1372 ? $this->makeList( $options['HAVING'], LIST_AND )
1373 : $options['HAVING'];
1374 $sql .= ' HAVING ' . $having;
1375 }
1376
1377 return $sql;
1378 }
1379
1380 /**
1381 * Returns an optional ORDER BY
1382 *
1383 * @param array $options Associative array of options
1384 * @return string
1385 * @see DatabaseBase::select()
1386 * @since 1.21
1387 */
1388 public function makeOrderBy( $options ) {
1389 if ( isset( $options['ORDER BY'] ) ) {
1390 $ob = is_array( $options['ORDER BY'] )
1391 ? implode( ',', $options['ORDER BY'] )
1392 : $options['ORDER BY'];
1393
1394 return ' ORDER BY ' . $ob;
1395 }
1396
1397 return '';
1398 }
1399
1400 // See IDatabase::select for the docs for this function
1401 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1402 $options = [], $join_conds = [] ) {
1403 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1404
1405 return $this->query( $sql, $fname );
1406 }
1407
1408 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1409 $options = [], $join_conds = []
1410 ) {
1411 if ( is_array( $vars ) ) {
1412 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1413 }
1414
1415 $options = (array)$options;
1416 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1417 ? $options['USE INDEX']
1418 : [];
1419 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1420 ? $options['IGNORE INDEX']
1421 : [];
1422
1423 if ( is_array( $table ) ) {
1424 $from = ' FROM ' .
1425 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1426 } elseif ( $table != '' ) {
1427 if ( $table[0] == ' ' ) {
1428 $from = ' FROM ' . $table;
1429 } else {
1430 $from = ' FROM ' .
1431 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1432 }
1433 } else {
1434 $from = '';
1435 }
1436
1437 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1438 $this->makeSelectOptions( $options );
1439
1440 if ( !empty( $conds ) ) {
1441 if ( is_array( $conds ) ) {
1442 $conds = $this->makeList( $conds, LIST_AND );
1443 }
1444 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1445 } else {
1446 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1447 }
1448
1449 if ( isset( $options['LIMIT'] ) ) {
1450 $sql = $this->limitResult( $sql, $options['LIMIT'],
1451 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1452 }
1453 $sql = "$sql $postLimitTail";
1454
1455 if ( isset( $options['EXPLAIN'] ) ) {
1456 $sql = 'EXPLAIN ' . $sql;
1457 }
1458
1459 return $sql;
1460 }
1461
1462 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1463 $options = [], $join_conds = []
1464 ) {
1465 $options = (array)$options;
1466 $options['LIMIT'] = 1;
1467 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1468
1469 if ( $res === false ) {
1470 return false;
1471 }
1472
1473 if ( !$this->numRows( $res ) ) {
1474 return false;
1475 }
1476
1477 $obj = $this->fetchObject( $res );
1478
1479 return $obj;
1480 }
1481
1482 public function estimateRowCount(
1483 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1484 ) {
1485 $rows = 0;
1486 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1487
1488 if ( $res ) {
1489 $row = $this->fetchRow( $res );
1490 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1491 }
1492
1493 return $rows;
1494 }
1495
1496 public function selectRowCount(
1497 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1498 ) {
1499 $rows = 0;
1500 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1501 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1502
1503 if ( $res ) {
1504 $row = $this->fetchRow( $res );
1505 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1506 }
1507
1508 return $rows;
1509 }
1510
1511 /**
1512 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1513 * It's only slightly flawed. Don't use for anything important.
1514 *
1515 * @param string $sql A SQL Query
1516 *
1517 * @return string
1518 */
1519 protected static function generalizeSQL( $sql ) {
1520 # This does the same as the regexp below would do, but in such a way
1521 # as to avoid crashing php on some large strings.
1522 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1523
1524 $sql = str_replace( "\\\\", '', $sql );
1525 $sql = str_replace( "\\'", '', $sql );
1526 $sql = str_replace( "\\\"", '', $sql );
1527 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1528 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1529
1530 # All newlines, tabs, etc replaced by single space
1531 $sql = preg_replace( '/\s+/', ' ', $sql );
1532
1533 # All numbers => N,
1534 # except the ones surrounded by characters, e.g. l10n
1535 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1536 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1537
1538 return $sql;
1539 }
1540
1541 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1542 $info = $this->fieldInfo( $table, $field );
1543
1544 return (bool)$info;
1545 }
1546
1547 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1548 if ( !$this->tableExists( $table ) ) {
1549 return null;
1550 }
1551
1552 $info = $this->indexInfo( $table, $index, $fname );
1553 if ( is_null( $info ) ) {
1554 return null;
1555 } else {
1556 return $info !== false;
1557 }
1558 }
1559
1560 public function tableExists( $table, $fname = __METHOD__ ) {
1561 $table = $this->tableName( $table );
1562 $old = $this->ignoreErrors( true );
1563 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1564 $this->ignoreErrors( $old );
1565
1566 return (bool)$res;
1567 }
1568
1569 public function indexUnique( $table, $index ) {
1570 $indexInfo = $this->indexInfo( $table, $index );
1571
1572 if ( !$indexInfo ) {
1573 return null;
1574 }
1575
1576 return !$indexInfo[0]->Non_unique;
1577 }
1578
1579 /**
1580 * Helper for DatabaseBase::insert().
1581 *
1582 * @param array $options
1583 * @return string
1584 */
1585 protected function makeInsertOptions( $options ) {
1586 return implode( ' ', $options );
1587 }
1588
1589 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1590 # No rows to insert, easy just return now
1591 if ( !count( $a ) ) {
1592 return true;
1593 }
1594
1595 $table = $this->tableName( $table );
1596
1597 if ( !is_array( $options ) ) {
1598 $options = [ $options ];
1599 }
1600
1601 $fh = null;
1602 if ( isset( $options['fileHandle'] ) ) {
1603 $fh = $options['fileHandle'];
1604 }
1605 $options = $this->makeInsertOptions( $options );
1606
1607 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1608 $multi = true;
1609 $keys = array_keys( $a[0] );
1610 } else {
1611 $multi = false;
1612 $keys = array_keys( $a );
1613 }
1614
1615 $sql = 'INSERT ' . $options .
1616 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1617
1618 if ( $multi ) {
1619 $first = true;
1620 foreach ( $a as $row ) {
1621 if ( $first ) {
1622 $first = false;
1623 } else {
1624 $sql .= ',';
1625 }
1626 $sql .= '(' . $this->makeList( $row ) . ')';
1627 }
1628 } else {
1629 $sql .= '(' . $this->makeList( $a ) . ')';
1630 }
1631
1632 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1633 return false;
1634 } elseif ( $fh !== null ) {
1635 return true;
1636 }
1637
1638 return (bool)$this->query( $sql, $fname );
1639 }
1640
1641 /**
1642 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1643 *
1644 * @param array $options
1645 * @return array
1646 */
1647 protected function makeUpdateOptionsArray( $options ) {
1648 if ( !is_array( $options ) ) {
1649 $options = [ $options ];
1650 }
1651
1652 $opts = [];
1653
1654 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1655 $opts[] = $this->lowPriorityOption();
1656 }
1657
1658 if ( in_array( 'IGNORE', $options ) ) {
1659 $opts[] = 'IGNORE';
1660 }
1661
1662 return $opts;
1663 }
1664
1665 /**
1666 * Make UPDATE options for the DatabaseBase::update function
1667 *
1668 * @param array $options The options passed to DatabaseBase::update
1669 * @return string
1670 */
1671 protected function makeUpdateOptions( $options ) {
1672 $opts = $this->makeUpdateOptionsArray( $options );
1673
1674 return implode( ' ', $opts );
1675 }
1676
1677 function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1678 $table = $this->tableName( $table );
1679 $opts = $this->makeUpdateOptions( $options );
1680 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1681
1682 if ( $conds !== [] && $conds !== '*' ) {
1683 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1684 }
1685
1686 return $this->query( $sql, $fname );
1687 }
1688
1689 public function makeList( $a, $mode = LIST_COMMA ) {
1690 if ( !is_array( $a ) ) {
1691 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1692 }
1693
1694 $first = true;
1695 $list = '';
1696
1697 foreach ( $a as $field => $value ) {
1698 if ( !$first ) {
1699 if ( $mode == LIST_AND ) {
1700 $list .= ' AND ';
1701 } elseif ( $mode == LIST_OR ) {
1702 $list .= ' OR ';
1703 } else {
1704 $list .= ',';
1705 }
1706 } else {
1707 $first = false;
1708 }
1709
1710 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1711 $list .= "($value)";
1712 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1713 $list .= "$value";
1714 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1715 // Remove null from array to be handled separately if found
1716 $includeNull = false;
1717 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1718 $includeNull = true;
1719 unset( $value[$nullKey] );
1720 }
1721 if ( count( $value ) == 0 && !$includeNull ) {
1722 throw new InvalidArgumentException( __METHOD__ . ": empty input for field $field" );
1723 } elseif ( count( $value ) == 0 ) {
1724 // only check if $field is null
1725 $list .= "$field IS NULL";
1726 } else {
1727 // IN clause contains at least one valid element
1728 if ( $includeNull ) {
1729 // Group subconditions to ensure correct precedence
1730 $list .= '(';
1731 }
1732 if ( count( $value ) == 1 ) {
1733 // Special-case single values, as IN isn't terribly efficient
1734 // Don't necessarily assume the single key is 0; we don't
1735 // enforce linear numeric ordering on other arrays here.
1736 $value = array_values( $value )[0];
1737 $list .= $field . " = " . $this->addQuotes( $value );
1738 } else {
1739 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1740 }
1741 // if null present in array, append IS NULL
1742 if ( $includeNull ) {
1743 $list .= " OR $field IS NULL)";
1744 }
1745 }
1746 } elseif ( $value === null ) {
1747 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1748 $list .= "$field IS ";
1749 } elseif ( $mode == LIST_SET ) {
1750 $list .= "$field = ";
1751 }
1752 $list .= 'NULL';
1753 } else {
1754 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1755 $list .= "$field = ";
1756 }
1757 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1758 }
1759 }
1760
1761 return $list;
1762 }
1763
1764 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1765 $conds = [];
1766
1767 foreach ( $data as $base => $sub ) {
1768 if ( count( $sub ) ) {
1769 $conds[] = $this->makeList(
1770 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1771 LIST_AND );
1772 }
1773 }
1774
1775 if ( $conds ) {
1776 return $this->makeList( $conds, LIST_OR );
1777 } else {
1778 // Nothing to search for...
1779 return false;
1780 }
1781 }
1782
1783 /**
1784 * Return aggregated value alias
1785 *
1786 * @param array $valuedata
1787 * @param string $valuename
1788 *
1789 * @return string
1790 */
1791 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1792 return $valuename;
1793 }
1794
1795 public function bitNot( $field ) {
1796 return "(~$field)";
1797 }
1798
1799 public function bitAnd( $fieldLeft, $fieldRight ) {
1800 return "($fieldLeft & $fieldRight)";
1801 }
1802
1803 public function bitOr( $fieldLeft, $fieldRight ) {
1804 return "($fieldLeft | $fieldRight)";
1805 }
1806
1807 public function buildConcat( $stringList ) {
1808 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1809 }
1810
1811 public function buildGroupConcatField(
1812 $delim, $table, $field, $conds = '', $join_conds = []
1813 ) {
1814 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1815
1816 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1817 }
1818
1819 /**
1820 * @param string $field Field or column to cast
1821 * @return string
1822 * @since 1.28
1823 */
1824 public function buildStringCast( $field ) {
1825 return $field;
1826 }
1827
1828 public function selectDB( $db ) {
1829 # Stub. Shouldn't cause serious problems if it's not overridden, but
1830 # if your database engine supports a concept similar to MySQL's
1831 # databases you may as well.
1832 $this->mDBname = $db;
1833
1834 return true;
1835 }
1836
1837 public function getDBname() {
1838 return $this->mDBname;
1839 }
1840
1841 public function getServer() {
1842 return $this->mServer;
1843 }
1844
1845 /**
1846 * Format a table name ready for use in constructing an SQL query
1847 *
1848 * This does two important things: it quotes the table names to clean them up,
1849 * and it adds a table prefix if only given a table name with no quotes.
1850 *
1851 * All functions of this object which require a table name call this function
1852 * themselves. Pass the canonical name to such functions. This is only needed
1853 * when calling query() directly.
1854 *
1855 * @note This function does not sanitize user input. It is not safe to use
1856 * this function to escape user input.
1857 * @param string $name Database table name
1858 * @param string $format One of:
1859 * quoted - Automatically pass the table name through addIdentifierQuotes()
1860 * so that it can be used in a query.
1861 * raw - Do not add identifier quotes to the table name
1862 * @return string Full database name
1863 */
1864 public function tableName( $name, $format = 'quoted' ) {
1865 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1866 # Skip the entire process when we have a string quoted on both ends.
1867 # Note that we check the end so that we will still quote any use of
1868 # use of `database`.table. But won't break things if someone wants
1869 # to query a database table with a dot in the name.
1870 if ( $this->isQuotedIdentifier( $name ) ) {
1871 return $name;
1872 }
1873
1874 # Lets test for any bits of text that should never show up in a table
1875 # name. Basically anything like JOIN or ON which are actually part of
1876 # SQL queries, but may end up inside of the table value to combine
1877 # sql. Such as how the API is doing.
1878 # Note that we use a whitespace test rather than a \b test to avoid
1879 # any remote case where a word like on may be inside of a table name
1880 # surrounded by symbols which may be considered word breaks.
1881 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1882 return $name;
1883 }
1884
1885 # Split database and table into proper variables.
1886 # We reverse the explode so that database.table and table both output
1887 # the correct table.
1888 $dbDetails = explode( '.', $name, 3 );
1889 if ( count( $dbDetails ) == 3 ) {
1890 list( $database, $schema, $table ) = $dbDetails;
1891 # We don't want any prefix added in this case
1892 $prefix = '';
1893 } elseif ( count( $dbDetails ) == 2 ) {
1894 list( $database, $table ) = $dbDetails;
1895 # We don't want any prefix added in this case
1896 # In dbs that support it, $database may actually be the schema
1897 # but that doesn't affect any of the functionality here
1898 $prefix = '';
1899 $schema = null;
1900 } else {
1901 list( $table ) = $dbDetails;
1902 if ( $wgSharedDB !== null # We have a shared database
1903 && $this->mForeign == false # We're not working on a foreign database
1904 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1905 && in_array( $table, $wgSharedTables ) # A shared table is selected
1906 ) {
1907 $database = $wgSharedDB;
1908 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
1909 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
1910 } else {
1911 $database = null;
1912 $schema = $this->mSchema; # Default schema
1913 $prefix = $this->mTablePrefix; # Default prefix
1914 }
1915 }
1916
1917 # Quote $table and apply the prefix if not quoted.
1918 # $tableName might be empty if this is called from Database::replaceVars()
1919 $tableName = "{$prefix}{$table}";
1920 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1921 $tableName = $this->addIdentifierQuotes( $tableName );
1922 }
1923
1924 # Quote $schema and merge it with the table name if needed
1925 if ( strlen( $schema ) ) {
1926 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1927 $schema = $this->addIdentifierQuotes( $schema );
1928 }
1929 $tableName = $schema . '.' . $tableName;
1930 }
1931
1932 # Quote $database and merge it with the table name if needed
1933 if ( $database !== null ) {
1934 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1935 $database = $this->addIdentifierQuotes( $database );
1936 }
1937 $tableName = $database . '.' . $tableName;
1938 }
1939
1940 return $tableName;
1941 }
1942
1943 /**
1944 * Fetch a number of table names into an array
1945 * This is handy when you need to construct SQL for joins
1946 *
1947 * Example:
1948 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1949 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1950 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1951 *
1952 * @return array
1953 */
1954 public function tableNames() {
1955 $inArray = func_get_args();
1956 $retVal = [];
1957
1958 foreach ( $inArray as $name ) {
1959 $retVal[$name] = $this->tableName( $name );
1960 }
1961
1962 return $retVal;
1963 }
1964
1965 /**
1966 * Fetch a number of table names into an zero-indexed numerical array
1967 * This is handy when you need to construct SQL for joins
1968 *
1969 * Example:
1970 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1971 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1972 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1973 *
1974 * @return array
1975 */
1976 public function tableNamesN() {
1977 $inArray = func_get_args();
1978 $retVal = [];
1979
1980 foreach ( $inArray as $name ) {
1981 $retVal[] = $this->tableName( $name );
1982 }
1983
1984 return $retVal;
1985 }
1986
1987 /**
1988 * Get an aliased table name
1989 * e.g. tableName AS newTableName
1990 *
1991 * @param string $name Table name, see tableName()
1992 * @param string|bool $alias Alias (optional)
1993 * @return string SQL name for aliased table. Will not alias a table to its own name
1994 */
1995 public function tableNameWithAlias( $name, $alias = false ) {
1996 if ( !$alias || $alias == $name ) {
1997 return $this->tableName( $name );
1998 } else {
1999 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2000 }
2001 }
2002
2003 /**
2004 * Gets an array of aliased table names
2005 *
2006 * @param array $tables [ [alias] => table ]
2007 * @return string[] See tableNameWithAlias()
2008 */
2009 public function tableNamesWithAlias( $tables ) {
2010 $retval = [];
2011 foreach ( $tables as $alias => $table ) {
2012 if ( is_numeric( $alias ) ) {
2013 $alias = $table;
2014 }
2015 $retval[] = $this->tableNameWithAlias( $table, $alias );
2016 }
2017
2018 return $retval;
2019 }
2020
2021 /**
2022 * Get an aliased field name
2023 * e.g. fieldName AS newFieldName
2024 *
2025 * @param string $name Field name
2026 * @param string|bool $alias Alias (optional)
2027 * @return string SQL name for aliased field. Will not alias a field to its own name
2028 */
2029 public function fieldNameWithAlias( $name, $alias = false ) {
2030 if ( !$alias || (string)$alias === (string)$name ) {
2031 return $name;
2032 } else {
2033 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2034 }
2035 }
2036
2037 /**
2038 * Gets an array of aliased field names
2039 *
2040 * @param array $fields [ [alias] => field ]
2041 * @return string[] See fieldNameWithAlias()
2042 */
2043 public function fieldNamesWithAlias( $fields ) {
2044 $retval = [];
2045 foreach ( $fields as $alias => $field ) {
2046 if ( is_numeric( $alias ) ) {
2047 $alias = $field;
2048 }
2049 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2050 }
2051
2052 return $retval;
2053 }
2054
2055 /**
2056 * Get the aliased table name clause for a FROM clause
2057 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2058 *
2059 * @param array $tables ( [alias] => table )
2060 * @param array $use_index Same as for select()
2061 * @param array $ignore_index Same as for select()
2062 * @param array $join_conds Same as for select()
2063 * @return string
2064 */
2065 protected function tableNamesWithIndexClauseOrJOIN(
2066 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2067 ) {
2068 $ret = [];
2069 $retJOIN = [];
2070 $use_index = (array)$use_index;
2071 $ignore_index = (array)$ignore_index;
2072 $join_conds = (array)$join_conds;
2073
2074 foreach ( $tables as $alias => $table ) {
2075 if ( !is_string( $alias ) ) {
2076 // No alias? Set it equal to the table name
2077 $alias = $table;
2078 }
2079 // Is there a JOIN clause for this table?
2080 if ( isset( $join_conds[$alias] ) ) {
2081 list( $joinType, $conds ) = $join_conds[$alias];
2082 $tableClause = $joinType;
2083 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2084 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2085 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2086 if ( $use != '' ) {
2087 $tableClause .= ' ' . $use;
2088 }
2089 }
2090 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2091 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2092 if ( $ignore != '' ) {
2093 $tableClause .= ' ' . $ignore;
2094 }
2095 }
2096 $on = $this->makeList( (array)$conds, LIST_AND );
2097 if ( $on != '' ) {
2098 $tableClause .= ' ON (' . $on . ')';
2099 }
2100
2101 $retJOIN[] = $tableClause;
2102 } elseif ( isset( $use_index[$alias] ) ) {
2103 // Is there an INDEX clause for this table?
2104 $tableClause = $this->tableNameWithAlias( $table, $alias );
2105 $tableClause .= ' ' . $this->useIndexClause(
2106 implode( ',', (array)$use_index[$alias] )
2107 );
2108
2109 $ret[] = $tableClause;
2110 } elseif ( isset( $ignore_index[$alias] ) ) {
2111 // Is there an INDEX clause for this table?
2112 $tableClause = $this->tableNameWithAlias( $table, $alias );
2113 $tableClause .= ' ' . $this->ignoreIndexClause(
2114 implode( ',', (array)$ignore_index[$alias] )
2115 );
2116
2117 $ret[] = $tableClause;
2118 } else {
2119 $tableClause = $this->tableNameWithAlias( $table, $alias );
2120
2121 $ret[] = $tableClause;
2122 }
2123 }
2124
2125 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2126 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2127 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2128
2129 // Compile our final table clause
2130 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2131 }
2132
2133 /**
2134 * Get the name of an index in a given table.
2135 *
2136 * @param string $index
2137 * @return string
2138 */
2139 protected function indexName( $index ) {
2140 // Backwards-compatibility hack
2141 $renamed = [
2142 'ar_usertext_timestamp' => 'usertext_timestamp',
2143 'un_user_id' => 'user_id',
2144 'un_user_ip' => 'user_ip',
2145 ];
2146
2147 if ( isset( $renamed[$index] ) ) {
2148 return $renamed[$index];
2149 } else {
2150 return $index;
2151 }
2152 }
2153
2154 public function addQuotes( $s ) {
2155 if ( $s instanceof Blob ) {
2156 $s = $s->fetch();
2157 }
2158 if ( $s === null ) {
2159 return 'NULL';
2160 } else {
2161 # This will also quote numeric values. This should be harmless,
2162 # and protects against weird problems that occur when they really
2163 # _are_ strings such as article titles and string->number->string
2164 # conversion is not 1:1.
2165 return "'" . $this->strencode( $s ) . "'";
2166 }
2167 }
2168
2169 /**
2170 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2171 * MySQL uses `backticks` while basically everything else uses double quotes.
2172 * Since MySQL is the odd one out here the double quotes are our generic
2173 * and we implement backticks in DatabaseMysql.
2174 *
2175 * @param string $s
2176 * @return string
2177 */
2178 public function addIdentifierQuotes( $s ) {
2179 return '"' . str_replace( '"', '""', $s ) . '"';
2180 }
2181
2182 /**
2183 * Returns if the given identifier looks quoted or not according to
2184 * the database convention for quoting identifiers .
2185 *
2186 * @note Do not use this to determine if untrusted input is safe.
2187 * A malicious user can trick this function.
2188 * @param string $name
2189 * @return bool
2190 */
2191 public function isQuotedIdentifier( $name ) {
2192 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2193 }
2194
2195 /**
2196 * @param string $s
2197 * @return string
2198 */
2199 protected function escapeLikeInternal( $s ) {
2200 return addcslashes( $s, '\%_' );
2201 }
2202
2203 public function buildLike() {
2204 $params = func_get_args();
2205
2206 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2207 $params = $params[0];
2208 }
2209
2210 $s = '';
2211
2212 foreach ( $params as $value ) {
2213 if ( $value instanceof LikeMatch ) {
2214 $s .= $value->toString();
2215 } else {
2216 $s .= $this->escapeLikeInternal( $value );
2217 }
2218 }
2219
2220 return " LIKE {$this->addQuotes( $s )} ";
2221 }
2222
2223 public function anyChar() {
2224 return new LikeMatch( '_' );
2225 }
2226
2227 public function anyString() {
2228 return new LikeMatch( '%' );
2229 }
2230
2231 public function nextSequenceValue( $seqName ) {
2232 return null;
2233 }
2234
2235 /**
2236 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2237 * is only needed because a) MySQL must be as efficient as possible due to
2238 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2239 * which index to pick. Anyway, other databases might have different
2240 * indexes on a given table. So don't bother overriding this unless you're
2241 * MySQL.
2242 * @param string $index
2243 * @return string
2244 */
2245 public function useIndexClause( $index ) {
2246 return '';
2247 }
2248
2249 /**
2250 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2251 * is only needed because a) MySQL must be as efficient as possible due to
2252 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2253 * which index to pick. Anyway, other databases might have different
2254 * indexes on a given table. So don't bother overriding this unless you're
2255 * MySQL.
2256 * @param string $index
2257 * @return string
2258 */
2259 public function ignoreIndexClause( $index ) {
2260 return '';
2261 }
2262
2263 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2264 $quotedTable = $this->tableName( $table );
2265
2266 if ( count( $rows ) == 0 ) {
2267 return;
2268 }
2269
2270 # Single row case
2271 if ( !is_array( reset( $rows ) ) ) {
2272 $rows = [ $rows ];
2273 }
2274
2275 // @FXIME: this is not atomic, but a trx would break affectedRows()
2276 foreach ( $rows as $row ) {
2277 # Delete rows which collide
2278 if ( $uniqueIndexes ) {
2279 $sql = "DELETE FROM $quotedTable WHERE ";
2280 $first = true;
2281 foreach ( $uniqueIndexes as $index ) {
2282 if ( $first ) {
2283 $first = false;
2284 $sql .= '( ';
2285 } else {
2286 $sql .= ' ) OR ( ';
2287 }
2288 if ( is_array( $index ) ) {
2289 $first2 = true;
2290 foreach ( $index as $col ) {
2291 if ( $first2 ) {
2292 $first2 = false;
2293 } else {
2294 $sql .= ' AND ';
2295 }
2296 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2297 }
2298 } else {
2299 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2300 }
2301 }
2302 $sql .= ' )';
2303 $this->query( $sql, $fname );
2304 }
2305
2306 # Now insert the row
2307 $this->insert( $table, $row, $fname );
2308 }
2309 }
2310
2311 /**
2312 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2313 * statement.
2314 *
2315 * @param string $table Table name
2316 * @param array|string $rows Row(s) to insert
2317 * @param string $fname Caller function name
2318 *
2319 * @return ResultWrapper
2320 */
2321 protected function nativeReplace( $table, $rows, $fname ) {
2322 $table = $this->tableName( $table );
2323
2324 # Single row case
2325 if ( !is_array( reset( $rows ) ) ) {
2326 $rows = [ $rows ];
2327 }
2328
2329 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2330 $first = true;
2331
2332 foreach ( $rows as $row ) {
2333 if ( $first ) {
2334 $first = false;
2335 } else {
2336 $sql .= ',';
2337 }
2338
2339 $sql .= '(' . $this->makeList( $row ) . ')';
2340 }
2341
2342 return $this->query( $sql, $fname );
2343 }
2344
2345 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2346 $fname = __METHOD__
2347 ) {
2348 if ( !count( $rows ) ) {
2349 return true; // nothing to do
2350 }
2351
2352 if ( !is_array( reset( $rows ) ) ) {
2353 $rows = [ $rows ];
2354 }
2355
2356 if ( count( $uniqueIndexes ) ) {
2357 $clauses = []; // list WHERE clauses that each identify a single row
2358 foreach ( $rows as $row ) {
2359 foreach ( $uniqueIndexes as $index ) {
2360 $index = is_array( $index ) ? $index : [ $index ]; // columns
2361 $rowKey = []; // unique key to this row
2362 foreach ( $index as $column ) {
2363 $rowKey[$column] = $row[$column];
2364 }
2365 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2366 }
2367 }
2368 $where = [ $this->makeList( $clauses, LIST_OR ) ];
2369 } else {
2370 $where = false;
2371 }
2372
2373 $useTrx = !$this->mTrxLevel;
2374 if ( $useTrx ) {
2375 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2376 }
2377 try {
2378 # Update any existing conflicting row(s)
2379 if ( $where !== false ) {
2380 $ok = $this->update( $table, $set, $where, $fname );
2381 } else {
2382 $ok = true;
2383 }
2384 # Now insert any non-conflicting row(s)
2385 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2386 } catch ( Exception $e ) {
2387 if ( $useTrx ) {
2388 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2389 }
2390 throw $e;
2391 }
2392 if ( $useTrx ) {
2393 $this->commit( $fname, self::FLUSHING_INTERNAL );
2394 }
2395
2396 return $ok;
2397 }
2398
2399 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2400 $fname = __METHOD__
2401 ) {
2402 if ( !$conds ) {
2403 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2404 }
2405
2406 $delTable = $this->tableName( $delTable );
2407 $joinTable = $this->tableName( $joinTable );
2408 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2409 if ( $conds != '*' ) {
2410 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2411 }
2412 $sql .= ')';
2413
2414 $this->query( $sql, $fname );
2415 }
2416
2417 /**
2418 * Returns the size of a text field, or -1 for "unlimited"
2419 *
2420 * @param string $table
2421 * @param string $field
2422 * @return int
2423 */
2424 public function textFieldSize( $table, $field ) {
2425 $table = $this->tableName( $table );
2426 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2427 $res = $this->query( $sql, __METHOD__ );
2428 $row = $this->fetchObject( $res );
2429
2430 $m = [];
2431
2432 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2433 $size = $m[1];
2434 } else {
2435 $size = -1;
2436 }
2437
2438 return $size;
2439 }
2440
2441 /**
2442 * A string to insert into queries to show that they're low-priority, like
2443 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2444 * string and nothing bad should happen.
2445 *
2446 * @return string Returns the text of the low priority option if it is
2447 * supported, or a blank string otherwise
2448 */
2449 public function lowPriorityOption() {
2450 return '';
2451 }
2452
2453 public function delete( $table, $conds, $fname = __METHOD__ ) {
2454 if ( !$conds ) {
2455 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2456 }
2457
2458 $table = $this->tableName( $table );
2459 $sql = "DELETE FROM $table";
2460
2461 if ( $conds != '*' ) {
2462 if ( is_array( $conds ) ) {
2463 $conds = $this->makeList( $conds, LIST_AND );
2464 }
2465 $sql .= ' WHERE ' . $conds;
2466 }
2467
2468 return $this->query( $sql, $fname );
2469 }
2470
2471 public function insertSelect(
2472 $destTable, $srcTable, $varMap, $conds,
2473 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2474 ) {
2475 if ( $this->cliMode ) {
2476 // For massive migrations with downtime, we don't want to select everything
2477 // into memory and OOM, so do all this native on the server side if possible.
2478 return $this->nativeInsertSelect(
2479 $destTable,
2480 $srcTable,
2481 $varMap,
2482 $conds,
2483 $fname,
2484 $insertOptions,
2485 $selectOptions
2486 );
2487 }
2488
2489 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2490 // on only the master (without needing row-based-replication). It also makes it easy to
2491 // know how big the INSERT is going to be.
2492 $fields = [];
2493 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2494 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2495 }
2496 $selectOptions[] = 'FOR UPDATE';
2497 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2498 if ( !$res ) {
2499 return false;
2500 }
2501
2502 $rows = [];
2503 foreach ( $res as $row ) {
2504 $rows[] = (array)$row;
2505 }
2506
2507 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2508 }
2509
2510 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2511 $fname = __METHOD__,
2512 $insertOptions = [], $selectOptions = []
2513 ) {
2514 $destTable = $this->tableName( $destTable );
2515
2516 if ( !is_array( $insertOptions ) ) {
2517 $insertOptions = [ $insertOptions ];
2518 }
2519
2520 $insertOptions = $this->makeInsertOptions( $insertOptions );
2521
2522 if ( !is_array( $selectOptions ) ) {
2523 $selectOptions = [ $selectOptions ];
2524 }
2525
2526 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2527 $selectOptions );
2528
2529 if ( is_array( $srcTable ) ) {
2530 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2531 } else {
2532 $srcTable = $this->tableName( $srcTable );
2533 }
2534
2535 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2536 " SELECT $startOpts " . implode( ',', $varMap ) .
2537 " FROM $srcTable $useIndex $ignoreIndex ";
2538
2539 if ( $conds != '*' ) {
2540 if ( is_array( $conds ) ) {
2541 $conds = $this->makeList( $conds, LIST_AND );
2542 }
2543 $sql .= " WHERE $conds";
2544 }
2545
2546 $sql .= " $tailOpts";
2547
2548 return $this->query( $sql, $fname );
2549 }
2550
2551 /**
2552 * Construct a LIMIT query with optional offset. This is used for query
2553 * pages. The SQL should be adjusted so that only the first $limit rows
2554 * are returned. If $offset is provided as well, then the first $offset
2555 * rows should be discarded, and the next $limit rows should be returned.
2556 * If the result of the query is not ordered, then the rows to be returned
2557 * are theoretically arbitrary.
2558 *
2559 * $sql is expected to be a SELECT, if that makes a difference.
2560 *
2561 * The version provided by default works in MySQL and SQLite. It will very
2562 * likely need to be overridden for most other DBMSes.
2563 *
2564 * @param string $sql SQL query we will append the limit too
2565 * @param int $limit The SQL limit
2566 * @param int|bool $offset The SQL offset (default false)
2567 * @throws DBUnexpectedError
2568 * @return string
2569 */
2570 public function limitResult( $sql, $limit, $offset = false ) {
2571 if ( !is_numeric( $limit ) ) {
2572 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2573 }
2574
2575 return "$sql LIMIT "
2576 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2577 . "{$limit} ";
2578 }
2579
2580 public function unionSupportsOrderAndLimit() {
2581 return true; // True for almost every DB supported
2582 }
2583
2584 public function unionQueries( $sqls, $all ) {
2585 $glue = $all ? ') UNION ALL (' : ') UNION (';
2586
2587 return '(' . implode( $glue, $sqls ) . ')';
2588 }
2589
2590 public function conditional( $cond, $trueVal, $falseVal ) {
2591 if ( is_array( $cond ) ) {
2592 $cond = $this->makeList( $cond, LIST_AND );
2593 }
2594
2595 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2596 }
2597
2598 public function strreplace( $orig, $old, $new ) {
2599 return "REPLACE({$orig}, {$old}, {$new})";
2600 }
2601
2602 public function getServerUptime() {
2603 return 0;
2604 }
2605
2606 public function wasDeadlock() {
2607 return false;
2608 }
2609
2610 public function wasLockTimeout() {
2611 return false;
2612 }
2613
2614 public function wasErrorReissuable() {
2615 return false;
2616 }
2617
2618 public function wasReadOnlyError() {
2619 return false;
2620 }
2621
2622 /**
2623 * Determines if the given query error was a connection drop
2624 * STUB
2625 *
2626 * @param integer|string $errno
2627 * @return bool
2628 */
2629 public function wasConnectionError( $errno ) {
2630 return false;
2631 }
2632
2633 /**
2634 * Perform a deadlock-prone transaction.
2635 *
2636 * This function invokes a callback function to perform a set of write
2637 * queries. If a deadlock occurs during the processing, the transaction
2638 * will be rolled back and the callback function will be called again.
2639 *
2640 * Avoid using this method outside of Job or Maintenance classes.
2641 *
2642 * Usage:
2643 * $dbw->deadlockLoop( callback, ... );
2644 *
2645 * Extra arguments are passed through to the specified callback function.
2646 * This method requires that no transactions are already active to avoid
2647 * causing premature commits or exceptions.
2648 *
2649 * Returns whatever the callback function returned on its successful,
2650 * iteration, or false on error, for example if the retry limit was
2651 * reached.
2652 *
2653 * @return mixed
2654 * @throws DBUnexpectedError
2655 * @throws Exception
2656 */
2657 public function deadlockLoop() {
2658 $args = func_get_args();
2659 $function = array_shift( $args );
2660 $tries = self::DEADLOCK_TRIES;
2661
2662 $this->begin( __METHOD__ );
2663
2664 $retVal = null;
2665 /** @var Exception $e */
2666 $e = null;
2667 do {
2668 try {
2669 $retVal = call_user_func_array( $function, $args );
2670 break;
2671 } catch ( DBQueryError $e ) {
2672 if ( $this->wasDeadlock() ) {
2673 // Retry after a randomized delay
2674 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2675 } else {
2676 // Throw the error back up
2677 throw $e;
2678 }
2679 }
2680 } while ( --$tries > 0 );
2681
2682 if ( $tries <= 0 ) {
2683 // Too many deadlocks; give up
2684 $this->rollback( __METHOD__ );
2685 throw $e;
2686 } else {
2687 $this->commit( __METHOD__ );
2688
2689 return $retVal;
2690 }
2691 }
2692
2693 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2694 # Real waits are implemented in the subclass.
2695 return 0;
2696 }
2697
2698 public function getSlavePos() {
2699 # Stub
2700 return false;
2701 }
2702
2703 public function getMasterPos() {
2704 # Stub
2705 return false;
2706 }
2707
2708 public function serverIsReadOnly() {
2709 return false;
2710 }
2711
2712 final public function onTransactionResolution( callable $callback ) {
2713 if ( !$this->mTrxLevel ) {
2714 throw new DBUnexpectedError( $this, "No transaction is active." );
2715 }
2716 $this->mTrxEndCallbacks[] = [ $callback, wfGetCaller() ];
2717 }
2718
2719 final public function onTransactionIdle( callable $callback ) {
2720 $this->mTrxIdleCallbacks[] = [ $callback, wfGetCaller() ];
2721 if ( !$this->mTrxLevel ) {
2722 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2723 }
2724 }
2725
2726 final public function onTransactionPreCommitOrIdle( callable $callback ) {
2727 if ( $this->mTrxLevel ) {
2728 $this->mTrxPreCommitCallbacks[] = [ $callback, wfGetCaller() ];
2729 } else {
2730 // If no transaction is active, then make one for this callback
2731 $this->startAtomic( __METHOD__ );
2732 try {
2733 call_user_func( $callback );
2734 $this->endAtomic( __METHOD__ );
2735 } catch ( Exception $e ) {
2736 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2737 throw $e;
2738 }
2739 }
2740 }
2741
2742 final public function setTransactionListener( $name, callable $callback = null ) {
2743 if ( $callback ) {
2744 $this->mTrxRecurringCallbacks[$name] = [ $callback, wfGetCaller() ];
2745 } else {
2746 unset( $this->mTrxRecurringCallbacks[$name] );
2747 }
2748 }
2749
2750 /**
2751 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2752 *
2753 * This method should not be used outside of Database/LoadBalancer
2754 *
2755 * @param bool $suppress
2756 * @since 1.28
2757 */
2758 final public function setTrxEndCallbackSuppression( $suppress ) {
2759 $this->mTrxEndCallbacksSuppressed = $suppress;
2760 }
2761
2762 /**
2763 * Actually run and consume any "on transaction idle/resolution" callbacks.
2764 *
2765 * This method should not be used outside of Database/LoadBalancer
2766 *
2767 * @param integer $trigger IDatabase::TRIGGER_* constant
2768 * @since 1.20
2769 * @throws Exception
2770 */
2771 public function runOnTransactionIdleCallbacks( $trigger ) {
2772 if ( $this->mTrxEndCallbacksSuppressed ) {
2773 return;
2774 }
2775
2776 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
2777 /** @var Exception $e */
2778 $e = null; // first exception
2779 do { // callbacks may add callbacks :)
2780 $callbacks = array_merge(
2781 $this->mTrxIdleCallbacks,
2782 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2783 );
2784 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2785 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2786 foreach ( $callbacks as $callback ) {
2787 try {
2788 list( $phpCallback ) = $callback;
2789 $this->clearFlag( DBO_TRX ); // make each query its own transaction
2790 call_user_func_array( $phpCallback, [ $trigger ] );
2791 if ( $autoTrx ) {
2792 $this->setFlag( DBO_TRX ); // restore automatic begin()
2793 } else {
2794 $this->clearFlag( DBO_TRX ); // restore auto-commit
2795 }
2796 } catch ( Exception $ex ) {
2797 call_user_func( $this->errorLogger, $ex );
2798 $e = $e ?: $ex;
2799 // Some callbacks may use startAtomic/endAtomic, so make sure
2800 // their transactions are ended so other callbacks don't fail
2801 if ( $this->trxLevel() ) {
2802 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2803 }
2804 }
2805 }
2806 } while ( count( $this->mTrxIdleCallbacks ) );
2807
2808 if ( $e instanceof Exception ) {
2809 throw $e; // re-throw any first exception
2810 }
2811 }
2812
2813 /**
2814 * Actually run and consume any "on transaction pre-commit" callbacks.
2815 *
2816 * This method should not be used outside of Database/LoadBalancer
2817 *
2818 * @since 1.22
2819 * @throws Exception
2820 */
2821 public function runOnTransactionPreCommitCallbacks() {
2822 $e = null; // first exception
2823 do { // callbacks may add callbacks :)
2824 $callbacks = $this->mTrxPreCommitCallbacks;
2825 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2826 foreach ( $callbacks as $callback ) {
2827 try {
2828 list( $phpCallback ) = $callback;
2829 call_user_func( $phpCallback );
2830 } catch ( Exception $ex ) {
2831 call_user_func( $this->errorLogger, $ex );
2832 $e = $e ?: $ex;
2833 }
2834 }
2835 } while ( count( $this->mTrxPreCommitCallbacks ) );
2836
2837 if ( $e instanceof Exception ) {
2838 throw $e; // re-throw any first exception
2839 }
2840 }
2841
2842 /**
2843 * Actually run any "transaction listener" callbacks.
2844 *
2845 * This method should not be used outside of Database/LoadBalancer
2846 *
2847 * @param integer $trigger IDatabase::TRIGGER_* constant
2848 * @throws Exception
2849 * @since 1.20
2850 */
2851 public function runTransactionListenerCallbacks( $trigger ) {
2852 if ( $this->mTrxEndCallbacksSuppressed ) {
2853 return;
2854 }
2855
2856 /** @var Exception $e */
2857 $e = null; // first exception
2858
2859 foreach ( $this->mTrxRecurringCallbacks as $callback ) {
2860 try {
2861 list( $phpCallback ) = $callback;
2862 $phpCallback( $trigger, $this );
2863 } catch ( Exception $ex ) {
2864 call_user_func( $this->errorLogger, $ex );
2865 $e = $e ?: $ex;
2866 }
2867 }
2868
2869 if ( $e instanceof Exception ) {
2870 throw $e; // re-throw any first exception
2871 }
2872 }
2873
2874 final public function startAtomic( $fname = __METHOD__ ) {
2875 if ( !$this->mTrxLevel ) {
2876 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2877 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2878 // in all changes being in one transaction to keep requests transactional.
2879 if ( !$this->getFlag( DBO_TRX ) ) {
2880 $this->mTrxAutomaticAtomic = true;
2881 }
2882 }
2883
2884 $this->mTrxAtomicLevels[] = $fname;
2885 }
2886
2887 final public function endAtomic( $fname = __METHOD__ ) {
2888 if ( !$this->mTrxLevel ) {
2889 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2890 }
2891 if ( !$this->mTrxAtomicLevels ||
2892 array_pop( $this->mTrxAtomicLevels ) !== $fname
2893 ) {
2894 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2895 }
2896
2897 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2898 $this->commit( $fname, self::FLUSHING_INTERNAL );
2899 }
2900 }
2901
2902 final public function doAtomicSection( $fname, callable $callback ) {
2903 $this->startAtomic( $fname );
2904 try {
2905 $res = call_user_func_array( $callback, [ $this, $fname ] );
2906 } catch ( Exception $e ) {
2907 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2908 throw $e;
2909 }
2910 $this->endAtomic( $fname );
2911
2912 return $res;
2913 }
2914
2915 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2916 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2917 if ( $this->mTrxLevel ) {
2918 if ( $this->mTrxAtomicLevels ) {
2919 $levels = implode( ', ', $this->mTrxAtomicLevels );
2920 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2921 throw new DBUnexpectedError( $this, $msg );
2922 } elseif ( !$this->mTrxAutomatic ) {
2923 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2924 throw new DBUnexpectedError( $this, $msg );
2925 } else {
2926 // @TODO: make this an exception at some point
2927 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2928 $this->queryLogger->error( $msg );
2929 return; // join the main transaction set
2930 }
2931 } elseif ( $this->getFlag( DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2932 // @TODO: make this an exception at some point
2933 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2934 $this->queryLogger->error( $msg );
2935 return; // let any writes be in the main transaction
2936 }
2937
2938 // Avoid fatals if close() was called
2939 $this->assertOpen();
2940
2941 $this->doBegin( $fname );
2942 $this->mTrxTimestamp = microtime( true );
2943 $this->mTrxFname = $fname;
2944 $this->mTrxDoneWrites = false;
2945 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2946 $this->mTrxAutomaticAtomic = false;
2947 $this->mTrxAtomicLevels = [];
2948 $this->mTrxShortId = wfRandomString( 12 );
2949 $this->mTrxWriteDuration = 0.0;
2950 $this->mTrxWriteQueryCount = 0;
2951 $this->mTrxWriteAdjDuration = 0.0;
2952 $this->mTrxWriteAdjQueryCount = 0;
2953 $this->mTrxWriteCallers = [];
2954 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2955 // Get an estimate of the replica DB lag before then, treating estimate staleness
2956 // as lag itself just to be safe
2957 $status = $this->getApproximateLagStatus();
2958 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2959 }
2960
2961 /**
2962 * Issues the BEGIN command to the database server.
2963 *
2964 * @see DatabaseBase::begin()
2965 * @param string $fname
2966 */
2967 protected function doBegin( $fname ) {
2968 $this->query( 'BEGIN', $fname );
2969 $this->mTrxLevel = 1;
2970 }
2971
2972 final public function commit( $fname = __METHOD__, $flush = '' ) {
2973 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2974 // There are still atomic sections open. This cannot be ignored
2975 $levels = implode( ', ', $this->mTrxAtomicLevels );
2976 throw new DBUnexpectedError(
2977 $this,
2978 "$fname: Got COMMIT while atomic sections $levels are still open."
2979 );
2980 }
2981
2982 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2983 if ( !$this->mTrxLevel ) {
2984 return; // nothing to do
2985 } elseif ( !$this->mTrxAutomatic ) {
2986 throw new DBUnexpectedError(
2987 $this,
2988 "$fname: Flushing an explicit transaction, getting out of sync."
2989 );
2990 }
2991 } else {
2992 if ( !$this->mTrxLevel ) {
2993 $this->queryLogger->error( "$fname: No transaction to commit, something got out of sync." );
2994 return; // nothing to do
2995 } elseif ( $this->mTrxAutomatic ) {
2996 // @TODO: make this an exception at some point
2997 $msg = "$fname: Explicit commit of implicit transaction.";
2998 $this->queryLogger->error( $msg );
2999 return; // wait for the main transaction set commit round
3000 }
3001 }
3002
3003 // Avoid fatals if close() was called
3004 $this->assertOpen();
3005
3006 $this->runOnTransactionPreCommitCallbacks();
3007 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
3008 $this->doCommit( $fname );
3009 if ( $this->mTrxDoneWrites ) {
3010 $this->mDoneWrites = microtime( true );
3011 $this->trxProfiler->transactionWritingOut(
3012 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3013 }
3014
3015 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
3016 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
3017 }
3018
3019 /**
3020 * Issues the COMMIT command to the database server.
3021 *
3022 * @see DatabaseBase::commit()
3023 * @param string $fname
3024 */
3025 protected function doCommit( $fname ) {
3026 if ( $this->mTrxLevel ) {
3027 $this->query( 'COMMIT', $fname );
3028 $this->mTrxLevel = 0;
3029 }
3030 }
3031
3032 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3033 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3034 if ( !$this->mTrxLevel ) {
3035 return; // nothing to do
3036 }
3037 } else {
3038 if ( !$this->mTrxLevel ) {
3039 $this->queryLogger->error(
3040 "$fname: No transaction to rollback, something got out of sync." );
3041 return; // nothing to do
3042 } elseif ( $this->getFlag( DBO_TRX ) ) {
3043 throw new DBUnexpectedError(
3044 $this,
3045 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3046 );
3047 }
3048 }
3049
3050 // Avoid fatals if close() was called
3051 $this->assertOpen();
3052
3053 $this->doRollback( $fname );
3054 $this->mTrxAtomicLevels = [];
3055 if ( $this->mTrxDoneWrites ) {
3056 $this->trxProfiler->transactionWritingOut(
3057 $this->mServer, $this->mDBname, $this->mTrxShortId );
3058 }
3059
3060 $this->mTrxIdleCallbacks = []; // clear
3061 $this->mTrxPreCommitCallbacks = []; // clear
3062 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
3063 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
3064 }
3065
3066 /**
3067 * Issues the ROLLBACK command to the database server.
3068 *
3069 * @see DatabaseBase::rollback()
3070 * @param string $fname
3071 */
3072 protected function doRollback( $fname ) {
3073 if ( $this->mTrxLevel ) {
3074 # Disconnects cause rollback anyway, so ignore those errors
3075 $ignoreErrors = true;
3076 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3077 $this->mTrxLevel = 0;
3078 }
3079 }
3080
3081 public function flushSnapshot( $fname = __METHOD__ ) {
3082 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
3083 // This only flushes transactions to clear snapshots, not to write data
3084 throw new DBUnexpectedError(
3085 $this,
3086 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3087 );
3088 }
3089
3090 $this->commit( $fname, self::FLUSHING_INTERNAL );
3091 }
3092
3093 public function explicitTrxActive() {
3094 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
3095 }
3096
3097 /**
3098 * Creates a new table with structure copied from existing table
3099 * Note that unlike most database abstraction functions, this function does not
3100 * automatically append database prefix, because it works at a lower
3101 * abstraction level.
3102 * The table names passed to this function shall not be quoted (this
3103 * function calls addIdentifierQuotes when needed).
3104 *
3105 * @param string $oldName Name of table whose structure should be copied
3106 * @param string $newName Name of table to be created
3107 * @param bool $temporary Whether the new table should be temporary
3108 * @param string $fname Calling function name
3109 * @throws RuntimeException
3110 * @return bool True if operation was successful
3111 */
3112 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3113 $fname = __METHOD__
3114 ) {
3115 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3116 }
3117
3118 function listTables( $prefix = null, $fname = __METHOD__ ) {
3119 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3120 }
3121
3122 /**
3123 * Reset the views process cache set by listViews()
3124 * @since 1.22
3125 */
3126 final public function clearViewsCache() {
3127 $this->allViews = null;
3128 }
3129
3130 /**
3131 * Lists all the VIEWs in the database
3132 *
3133 * For caching purposes the list of all views should be stored in
3134 * $this->allViews. The process cache can be cleared with clearViewsCache()
3135 *
3136 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3137 * @param string $fname Name of calling function
3138 * @throws RuntimeException
3139 * @return array
3140 * @since 1.22
3141 */
3142 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3143 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3144 }
3145
3146 /**
3147 * Differentiates between a TABLE and a VIEW
3148 *
3149 * @param string $name Name of the database-structure to test.
3150 * @throws RuntimeException
3151 * @return bool
3152 * @since 1.22
3153 */
3154 public function isView( $name ) {
3155 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3156 }
3157
3158 public function timestamp( $ts = 0 ) {
3159 return wfTimestamp( TS_MW, $ts );
3160 }
3161
3162 public function timestampOrNull( $ts = null ) {
3163 if ( is_null( $ts ) ) {
3164 return null;
3165 } else {
3166 return $this->timestamp( $ts );
3167 }
3168 }
3169
3170 /**
3171 * Take the result from a query, and wrap it in a ResultWrapper if
3172 * necessary. Boolean values are passed through as is, to indicate success
3173 * of write queries or failure.
3174 *
3175 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3176 * resource, and it was necessary to call this function to convert it to
3177 * a wrapper. Nowadays, raw database objects are never exposed to external
3178 * callers, so this is unnecessary in external code.
3179 *
3180 * @param bool|ResultWrapper|resource|object $result
3181 * @return bool|ResultWrapper
3182 */
3183 protected function resultObject( $result ) {
3184 if ( !$result ) {
3185 return false;
3186 } elseif ( $result instanceof ResultWrapper ) {
3187 return $result;
3188 } elseif ( $result === true ) {
3189 // Successful write query
3190 return $result;
3191 } else {
3192 return new ResultWrapper( $this, $result );
3193 }
3194 }
3195
3196 public function ping( &$rtt = null ) {
3197 // Avoid hitting the server if it was hit recently
3198 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
3199 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
3200 $rtt = $this->mRTTEstimate;
3201 return true; // don't care about $rtt
3202 }
3203 }
3204
3205 // This will reconnect if possible or return false if not
3206 $this->clearFlag( DBO_TRX, self::REMEMBER_PRIOR );
3207 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
3208 $this->restoreFlags( self::RESTORE_PRIOR );
3209
3210 if ( $ok ) {
3211 $rtt = $this->mRTTEstimate;
3212 }
3213
3214 return $ok;
3215 }
3216
3217 /**
3218 * @return bool
3219 */
3220 protected function reconnect() {
3221 $this->closeConnection();
3222 $this->mOpened = false;
3223 $this->mConn = false;
3224 try {
3225 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3226 $this->lastPing = microtime( true );
3227 $ok = true;
3228 } catch ( DBConnectionError $e ) {
3229 $ok = false;
3230 }
3231
3232 return $ok;
3233 }
3234
3235 public function getSessionLagStatus() {
3236 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3237 }
3238
3239 /**
3240 * Get the replica DB lag when the current transaction started
3241 *
3242 * This is useful when transactions might use snapshot isolation
3243 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3244 * is this lag plus transaction duration. If they don't, it is still
3245 * safe to be pessimistic. This returns null if there is no transaction.
3246 *
3247 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3248 * @since 1.27
3249 */
3250 public function getTransactionLagStatus() {
3251 return $this->mTrxLevel
3252 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
3253 : null;
3254 }
3255
3256 /**
3257 * Get a replica DB lag estimate for this server
3258 *
3259 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3260 * @since 1.27
3261 */
3262 public function getApproximateLagStatus() {
3263 return [
3264 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3265 'since' => microtime( true )
3266 ];
3267 }
3268
3269 /**
3270 * Merge the result of getSessionLagStatus() for several DBs
3271 * using the most pessimistic values to estimate the lag of
3272 * any data derived from them in combination
3273 *
3274 * This is information is useful for caching modules
3275 *
3276 * @see WANObjectCache::set()
3277 * @see WANObjectCache::getWithSetCallback()
3278 *
3279 * @param IDatabase $db1
3280 * @param IDatabase ...
3281 * @return array Map of values:
3282 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3283 * - since: oldest UNIX timestamp of any of the DB lag estimates
3284 * - pending: whether any of the DBs have uncommitted changes
3285 * @since 1.27
3286 */
3287 public static function getCacheSetOptions( IDatabase $db1 ) {
3288 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3289 foreach ( func_get_args() as $db ) {
3290 /** @var IDatabase $db */
3291 $status = $db->getSessionLagStatus();
3292 if ( $status['lag'] === false ) {
3293 $res['lag'] = false;
3294 } elseif ( $res['lag'] !== false ) {
3295 $res['lag'] = max( $res['lag'], $status['lag'] );
3296 }
3297 $res['since'] = min( $res['since'], $status['since'] );
3298 $res['pending'] = $res['pending'] ?: $db->writesPending();
3299 }
3300
3301 return $res;
3302 }
3303
3304 public function getLag() {
3305 return 0;
3306 }
3307
3308 function maxListLen() {
3309 return 0;
3310 }
3311
3312 public function encodeBlob( $b ) {
3313 return $b;
3314 }
3315
3316 public function decodeBlob( $b ) {
3317 if ( $b instanceof Blob ) {
3318 $b = $b->fetch();
3319 }
3320 return $b;
3321 }
3322
3323 public function setSessionOptions( array $options ) {
3324 }
3325
3326 /**
3327 * Read and execute SQL commands from a file.
3328 *
3329 * Returns true on success, error string or exception on failure (depending
3330 * on object's error ignore settings).
3331 *
3332 * @param string $filename File name to open
3333 * @param bool|callable $lineCallback Optional function called before reading each line
3334 * @param bool|callable $resultCallback Optional function called for each MySQL result
3335 * @param bool|string $fname Calling function name or false if name should be
3336 * generated dynamically using $filename
3337 * @param bool|callable $inputCallback Optional function called for each
3338 * complete line sent
3339 * @return bool|string
3340 * @throws Exception
3341 */
3342 public function sourceFile(
3343 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3344 ) {
3345 MediaWiki\suppressWarnings();
3346 $fp = fopen( $filename, 'r' );
3347 MediaWiki\restoreWarnings();
3348
3349 if ( false === $fp ) {
3350 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3351 }
3352
3353 if ( !$fname ) {
3354 $fname = __METHOD__ . "( $filename )";
3355 }
3356
3357 try {
3358 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3359 } catch ( Exception $e ) {
3360 fclose( $fp );
3361 throw $e;
3362 }
3363
3364 fclose( $fp );
3365
3366 return $error;
3367 }
3368
3369 /**
3370 * Get the full path of a patch file. Originally based on archive()
3371 * from updaters.inc. Keep in mind this always returns a patch, as
3372 * it fails back to MySQL if no DB-specific patch can be found
3373 *
3374 * @param string $patch The name of the patch, like patch-something.sql
3375 * @return string Full path to patch file
3376 */
3377 public function patchPath( $patch ) {
3378 global $IP;
3379
3380 $dbType = $this->getType();
3381 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3382 return "$IP/maintenance/$dbType/archives/$patch";
3383 } else {
3384 return "$IP/maintenance/archives/$patch";
3385 }
3386 }
3387
3388 public function setSchemaVars( $vars ) {
3389 $this->mSchemaVars = $vars;
3390 }
3391
3392 /**
3393 * Read and execute commands from an open file handle.
3394 *
3395 * Returns true on success, error string or exception on failure (depending
3396 * on object's error ignore settings).
3397 *
3398 * @param resource $fp File handle
3399 * @param bool|callable $lineCallback Optional function called before reading each query
3400 * @param bool|callable $resultCallback Optional function called for each MySQL result
3401 * @param string $fname Calling function name
3402 * @param bool|callable $inputCallback Optional function called for each complete query sent
3403 * @return bool|string
3404 */
3405 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3406 $fname = __METHOD__, $inputCallback = false
3407 ) {
3408 $cmd = '';
3409
3410 while ( !feof( $fp ) ) {
3411 if ( $lineCallback ) {
3412 call_user_func( $lineCallback );
3413 }
3414
3415 $line = trim( fgets( $fp ) );
3416
3417 if ( $line == '' ) {
3418 continue;
3419 }
3420
3421 if ( '-' == $line[0] && '-' == $line[1] ) {
3422 continue;
3423 }
3424
3425 if ( $cmd != '' ) {
3426 $cmd .= ' ';
3427 }
3428
3429 $done = $this->streamStatementEnd( $cmd, $line );
3430
3431 $cmd .= "$line\n";
3432
3433 if ( $done || feof( $fp ) ) {
3434 $cmd = $this->replaceVars( $cmd );
3435
3436 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3437 $res = $this->query( $cmd, $fname );
3438
3439 if ( $resultCallback ) {
3440 call_user_func( $resultCallback, $res, $this );
3441 }
3442
3443 if ( false === $res ) {
3444 $err = $this->lastError();
3445
3446 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3447 }
3448 }
3449 $cmd = '';
3450 }
3451 }
3452
3453 return true;
3454 }
3455
3456 /**
3457 * Called by sourceStream() to check if we've reached a statement end
3458 *
3459 * @param string $sql SQL assembled so far
3460 * @param string $newLine New line about to be added to $sql
3461 * @return bool Whether $newLine contains end of the statement
3462 */
3463 public function streamStatementEnd( &$sql, &$newLine ) {
3464 if ( $this->delimiter ) {
3465 $prev = $newLine;
3466 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3467 if ( $newLine != $prev ) {
3468 return true;
3469 }
3470 }
3471
3472 return false;
3473 }
3474
3475 /**
3476 * Database independent variable replacement. Replaces a set of variables
3477 * in an SQL statement with their contents as given by $this->getSchemaVars().
3478 *
3479 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3480 *
3481 * - '{$var}' should be used for text and is passed through the database's
3482 * addQuotes method.
3483 * - `{$var}` should be used for identifiers (e.g. table and database names).
3484 * It is passed through the database's addIdentifierQuotes method which
3485 * can be overridden if the database uses something other than backticks.
3486 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3487 * database's tableName method.
3488 * - / *i* / passes the name that follows through the database's indexName method.
3489 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3490 * its use should be avoided. In 1.24 and older, string encoding was applied.
3491 *
3492 * @param string $ins SQL statement to replace variables in
3493 * @return string The new SQL statement with variables replaced
3494 */
3495 protected function replaceVars( $ins ) {
3496 $vars = $this->getSchemaVars();
3497 return preg_replace_callback(
3498 '!
3499 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3500 \'\{\$ (\w+) }\' | # 3. addQuotes
3501 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3502 /\*\$ (\w+) \*/ # 5. leave unencoded
3503 !x',
3504 function ( $m ) use ( $vars ) {
3505 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3506 // check for both nonexistent keys *and* the empty string.
3507 if ( isset( $m[1] ) && $m[1] !== '' ) {
3508 if ( $m[1] === 'i' ) {
3509 return $this->indexName( $m[2] );
3510 } else {
3511 return $this->tableName( $m[2] );
3512 }
3513 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3514 return $this->addQuotes( $vars[$m[3]] );
3515 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3516 return $this->addIdentifierQuotes( $vars[$m[4]] );
3517 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3518 return $vars[$m[5]];
3519 } else {
3520 return $m[0];
3521 }
3522 },
3523 $ins
3524 );
3525 }
3526
3527 /**
3528 * Get schema variables. If none have been set via setSchemaVars(), then
3529 * use some defaults from the current object.
3530 *
3531 * @return array
3532 */
3533 protected function getSchemaVars() {
3534 if ( $this->mSchemaVars ) {
3535 return $this->mSchemaVars;
3536 } else {
3537 return $this->getDefaultSchemaVars();
3538 }
3539 }
3540
3541 /**
3542 * Get schema variables to use if none have been set via setSchemaVars().
3543 *
3544 * Override this in derived classes to provide variables for tables.sql
3545 * and SQL patch files.
3546 *
3547 * @return array
3548 */
3549 protected function getDefaultSchemaVars() {
3550 return [];
3551 }
3552
3553 public function lockIsFree( $lockName, $method ) {
3554 return true;
3555 }
3556
3557 public function lock( $lockName, $method, $timeout = 5 ) {
3558 $this->mNamedLocksHeld[$lockName] = 1;
3559
3560 return true;
3561 }
3562
3563 public function unlock( $lockName, $method ) {
3564 unset( $this->mNamedLocksHeld[$lockName] );
3565
3566 return true;
3567 }
3568
3569 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3570 if ( $this->writesOrCallbacksPending() ) {
3571 // This only flushes transactions to clear snapshots, not to write data
3572 throw new DBUnexpectedError(
3573 $this,
3574 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3575 );
3576 }
3577
3578 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3579 return null;
3580 }
3581
3582 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3583 if ( $this->trxLevel() ) {
3584 // There is a good chance an exception was thrown, causing any early return
3585 // from the caller. Let any error handler get a chance to issue rollback().
3586 // If there isn't one, let the error bubble up and trigger server-side rollback.
3587 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3588 $this->unlock( $lockKey, $fname );
3589 } );
3590 } else {
3591 $this->unlock( $lockKey, $fname );
3592 }
3593 } );
3594
3595 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
3596
3597 return $unlocker;
3598 }
3599
3600 public function namedLocksEnqueue() {
3601 return false;
3602 }
3603
3604 /**
3605 * Lock specific tables
3606 *
3607 * @param array $read Array of tables to lock for read access
3608 * @param array $write Array of tables to lock for write access
3609 * @param string $method Name of caller
3610 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3611 * @return bool
3612 */
3613 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3614 return true;
3615 }
3616
3617 /**
3618 * Unlock specific tables
3619 *
3620 * @param string $method The caller
3621 * @return bool
3622 */
3623 public function unlockTables( $method ) {
3624 return true;
3625 }
3626
3627 /**
3628 * Delete a table
3629 * @param string $tableName
3630 * @param string $fName
3631 * @return bool|ResultWrapper
3632 * @since 1.18
3633 */
3634 public function dropTable( $tableName, $fName = __METHOD__ ) {
3635 if ( !$this->tableExists( $tableName, $fName ) ) {
3636 return false;
3637 }
3638 $sql = "DROP TABLE " . $this->tableName( $tableName );
3639 if ( $this->cascadingDeletes() ) {
3640 $sql .= " CASCADE";
3641 }
3642
3643 return $this->query( $sql, $fName );
3644 }
3645
3646 /**
3647 * Get search engine class. All subclasses of this need to implement this
3648 * if they wish to use searching.
3649 *
3650 * @return string
3651 */
3652 public function getSearchEngine() {
3653 return 'SearchEngineDummy';
3654 }
3655
3656 public function getInfinity() {
3657 return 'infinity';
3658 }
3659
3660 public function encodeExpiry( $expiry ) {
3661 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3662 ? $this->getInfinity()
3663 : $this->timestamp( $expiry );
3664 }
3665
3666 public function decodeExpiry( $expiry, $format = TS_MW ) {
3667 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3668 ? 'infinity'
3669 : wfTimestamp( $format, $expiry );
3670 }
3671
3672 public function setBigSelects( $value = true ) {
3673 // no-op
3674 }
3675
3676 public function isReadOnly() {
3677 return ( $this->getReadOnlyReason() !== false );
3678 }
3679
3680 /**
3681 * @return string|bool Reason this DB is read-only or false if it is not
3682 */
3683 protected function getReadOnlyReason() {
3684 $reason = $this->getLBInfo( 'readOnlyReason' );
3685
3686 return is_string( $reason ) ? $reason : false;
3687 }
3688
3689 /**
3690 * @since 1.19
3691 * @return string
3692 */
3693 public function __toString() {
3694 return (string)$this->mConn;
3695 }
3696
3697 /**
3698 * Run a few simple sanity checks
3699 */
3700 public function __destruct() {
3701 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3702 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3703 }
3704 $danglingCallbacks = array_merge(
3705 $this->mTrxIdleCallbacks,
3706 $this->mTrxPreCommitCallbacks,
3707 $this->mTrxEndCallbacks
3708 );
3709 if ( $danglingCallbacks ) {
3710 $callers = [];
3711 foreach ( $danglingCallbacks as $callbackInfo ) {
3712 $callers[] = $callbackInfo[1];
3713 }
3714 $callers = implode( ', ', $callers );
3715 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3716 }
3717 }
3718 }
3719
3720 /**
3721 * @since 1.27
3722 */
3723 abstract class Database extends DatabaseBase {
3724 // B/C until nothing type hints for DatabaseBase
3725 // @TODO: finish renaming DatabaseBase => Database
3726 }